How to use a function from another class in Java? [duplicate] - java

This question already has answers here:
Java how to call method in another class
(3 answers)
Calling static method from another java class
(3 answers)
Closed 2 years ago.
I know this is a repeated question but I don't really understand how to call upon the functions or the utility of all the privates etc... So what I'm trying to do is "build a bear" where u pick the size and colour in a different class while the main class calls it, like this:
Size
import java.util.Scanner;
public class BABSize
{
public static String size()
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like a small, medium or big bear?");
String size = input.nextLine();
input.close();
return size;
}
}
Colour
import java.util.Scanner;
public class BABColour
{
public static String Colour()
{
Scanner input = new Scanner(System.in);
System.out.println("What colour would u like your bear?");
String colour = input.nextLine();
input.close();
return colour;
}
}
Main
public class MainFunction
{
public static void main(String[] args)
{
BABColour c = new Colourr();
BABSize g = new Size();
System.out.println("Your " + g + "," + c + " bear will be ready in a moment:)");
}
}

Since you are making static functions, you dont need to create instance of those classes and directly call the static methods.
Not suggested but you can still have a call after creating instance of it and using that reference to call the method.
Try to observe what you are returning fron that function and have that reference in calling method.
For example: For asking which beer, you are returning String.
So, in main method have that reference of String.
String beer = BABSize.size();
Similarly for colour you are retuning String so have that in main method.

change it like this
public static void main(String[] args)
{
BABColour c = new BABColour();//here you create a variable of type Colour
BABSize g = new BABSize();
String color = c.Colour();//Here you call the method color
String size = g.Size();//Here you call the method to get the size
System.out.println("Your " + color + "," + size + " bear will be ready in a moment:)");
}
(Im open to any question you have obout this)

Related

Eclipse JAVA String reverse - reversing 1 word which is pre-declared [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
Like to know how to reverse a string value (1 word) which is pre-declared in the program. I mean not using user input or scanner.
Like to reverse a word "TRAIN" which is pre-declared in the program.
Have tried the below program but no results and no error also.
// QUERY PROGRAM NOT RUNNING - NO RESULT, NO ERROR.
// STRING REVERSE PROGRAM USING ARRAY
package abnpackage;
class Play {
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
Problem in Q=Q-- and ; symbol after for cylce. Try this:
class Play{
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q--) {
System.out.print(INPUT_WORD[Q]);
}
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
I'd like to offer a few suggestions.
Indent your code. It not only makes it easier for you to follow, but makes it easier for others to read your code.
Naming conventions. Use Title case for classes, camelCase for both variables and methods, and UPPER_CASE for constants.
Strings and characters. A String can be decomposed into an array of characters with the built-in method, String.toCharArray(). A character array is mutable, so is often used as an intermediate structure when converting a String from one state to another for tasks like ciphers or interview problems.
Encapsulation. If you can make your methods use only what is submitted to them through their method signature, and only output their return value, it's usually best. Prefer passing values over referencing constants in your utility methods to make them easier to follow.
package abnpackage;
class Play {
private static final String INPUT_WORD = "TRAIN";
private String reverse(String word) {
char[] letters=word.toCharArray();
StringBuilder sb=new StringBuilder();
for (int q=letters.length-1; q>=0; q--) {
sb.append(letters[q]);
}
return sb.toString();
}
public static void main(String[]args) {
Play play = new Play();
System.out.println("REVERSE VALUE: " + play.reverse(INPUT_WORD));
}
}
class Play {
void REVERSE() {
String[] INPUT_WORD = {"T", "R", "A", "I", "N"};
String[] OUTPUT_WORD =new String[INPUT_WORD.length];
int length = INPUT_WORD.length;
int i = 0;
while(--length>=0){
OUTPUT_WORD[i++] = INPUT_WORD[length];
}
System.out.println(Arrays.toString(OUTPUT_WORD));
}
public static void main(String[] args) {
Play PL = new Play();
PL.REVERSE();
}
}
Your code is entering an endless loop because of the assignment "Q=Q--"
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
It should instead be
Q--
without a semicolon at the end.
If the code runs successfully, it will print the words "REVERSE VALUE" repeatedly prior to printing each character in reverse.
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
So you will want to keep the text in reverse prior to printing the whole statement at the end of the execution of the for loop.
What is the reason to use array of String instead of just String? Since it's not mentioned as a requirement, I'm suggesting the following as an alternative solution:
public class Play {
static void reverse(){
String inputWord = "TRAIN";
char[] toStrArray = inputWord.toCharArray();
char[] revisedInput = new char[inputWord.length()];
int i = 0;
for(int q=toStrArray.length-1; q>=0; q--){
revisedInput[i]=toStrArray[q];
i++;
}
System.out.print ("REVERSE VALUE: " + new String(revisedInput));
}
public static void main(String[]args){
//Play PL = new Play();
//PL.REVERSE();
reverse();
}
}
Note: You can declare the method reverse as a static method. By doing this you don't have to create an object before calling it. Hope this helps.

How do I make a method work in my class in Java [duplicate]

This question already has answers here:
How to call a method in another class of the same package?
(8 answers)
Closed 7 years ago.
Hi I have a robot which I need to tell it to move a certain number of times forward by saying forward 5. I have the method, I just need to get it to work in my class. Here is the method:
public void moveNumOfTimes(int num)
{
//-----------------------------------------------------------------------------------------------
int i=0;
while(i<num) {
if (this.frontIsClear()){ // if the front is NOT clear the robot should not move, otherwise will collide into the wall
this.move();
}
i++; // same as i=i+1;
}
//-----------------------------------------------------------------------------------------------
}
How do I enter that in my program? Is it like this?
moveNumOfTimes(int num);
Hope someone can help. Thanks
You should use a Scanner object to take input from the console.
Scanner sc = new Scanner(System.in);
You can implement like this.
class Robot{
public static void main(String args[]){
Scanner sc = new Scanner();
int numOfSteps = sc.nextInt(); //This line takes a integer input from the user
YourClassName r = new YourClassName();
//DO any initialization operations here
r.moveNumOfTimes(numOfSteps);
//Post movement operations come here
}
You can learn more on scanner here
How do I enter that in my program? Is it like this?
moveNumOfTimes(int num);
Yes, you could use something similar to this if you were trying to pass a command in from another method call. Something like:
public void Control(int moveNumber) {
... some other code, do some other stuff...
moveNumOfTimes(moveNumber); //Here you are passing a parameter value to your original method;
}
Or you could control it directly with another method like:
public void moveFive() {
moveNumOfTimes(5);
}
More likely, however, you wouldn't want to hardcode a method but rather call your original method directly through your Main method.
public static void main(String [ ] args) {
Robot r = new Robot();
r.moveNumOfTimes(5); //Here you have moved your new robot!
}
And if you really want to get fancy, look into working with the System and Scanner classes so you can prompt your user to tell the robot how much to move:
public static void main(String [ ] args) {
Robot r = new Robot();
Scanner reader = new Scanner(System.in);
System.out.println("How far should the robot move?"); //Output to the console window
int input = reader.nextInt(); //Reads the next int value
r.moveNumOfTimes(input); //Calls your method using the scanned input
}

Java - Calling private arraylist from class [duplicate]

This question already has answers here:
Is it possible in Java to access private fields via reflection [duplicate]
(3 answers)
Closed 7 years ago.
My template opens with a menu of options and the user inputs something between 1-3 to select one of the three options.
When the user chooses option 1, it asks them to input a number teamNumber. One must instantiate the class Team, then it writes it to an arraylist.
If there is at least one number in numberList, the user can select option 2. It asks them to input any of the numbers from the arraylist and searches it. If the number they input is found, then you input a String teamMemberFirstName and a char firstInitialLastName. Then it will write the input to a private arraylist located in another class TeamMember.
Once they have input the info in option 1 and 2, they can choose option 3. It allows you to print the list of inputted names based on which team number you put them on.
I am not sure how, in option 3, to call the private arraylist from the TeamMember class teamList. Any guidance on how to proceed with this step? My code is below.
Main class:
public class Main {
public static void main(String[] args) {
int choosing;
Scanner scan = new Scanner(System.in);
String input;
int teamNumber;
boolean stayInLoop;
ArrayList<Team> numberList = new ArrayList<Team>();
do {
stayInLoop = true;
System.out.println("1. Add a new team");
System.out.println("2. Add a new team member");
System.out.println("3. View teams");
input = scan.nextLine();
if (input.equals("1")) {
System.out.println("Enter a team number:");
teamNumber = scan.nextInt();
scan.nextLine();
Team addTeam = new Team(teamNumber);
numberList.add(addTeam);
}
if (input.equals("2")){
boolean foundIt = false;
boolean valid = true;
System.out.println("Team number:");
teamNumber = scan.nextInt();
scan.nextLine();
for (int a = 0; a < numberList.size() && foundIt == false; a++){
Team addTeam = numberList.get(a);
if (addTeam.findTeam() == teamNumber) {
foundIt = true;
System.out.println("Enter first name of team member:");
String teamMemberFirstName = scan.nextLine();
System.out.println("Enter first initial of last name:");
char firstInitialLastName = scan.nextLine().charAt(0);
TeamMember inputTeamMember = new TeamMember(teamMemberFirstName, firstInitialLastName);
inputTeamMember.addMember(inputTeamMember, valid = true);
System.out.println("Success!");
}
}
if (foundIt == false) {
System.out.println("Try again.");
}
}
if (input.equals("3")){
for (int a = 0; a < numberList.size(); a++) {
Team addTeam = numberList.get(a);
//Not sure what to put where there are ????'s - I tried a few ideas and stuff I found online, but nothing worked
//I assume I call the method/class here????
System.out.println("Team: " + addTeam.findTeam() + " Members: " +
"I will put the member called from the arraylist here????");
}
}
}while (stayInLoop == true;)
}}
TeamMember class:
public class TeamMember {
private final String teamMemberFirstName;
private final char firstInitialLastName;
private ArrayList<TeamMember> teamList = new ArrayList<>();
public TeamMember(String teamMemberFirstName, char firstInitialLastName) {
this.teamMemberFirstName = teamMemberFirstName;
this.firstInitialLastName = firstInitialLastName;
}
public int addMember(TeamMember member, boolean valid) {
valid = teamList.add(member);
return teamList.size();
}
}
You cannot directly access private fields from other classes. Either move your list to the Team class or create a getter to retrieve the list.
In a public class, you can return a private object in a public method. This seems like the easiest way in this project. Add a new method to your TeamMember class, and have it return teamList:
//inside your TeamMember class, anywhere after you assign the private variable
public static ArrayList show(){
//the static keyword, in short, will make the method callable without a class instance.
return teamList;
}
Since the TeamMember method show() is now static, you should be able to simply call TeamMember.show() and get the ArrayList.
Important note: In order for this to work, you must make the private arraylist static too. A static object cannot call a non-static object.
This will turn it into private static ArrayList<TeamMember> teamList = new ArrayList<>();
In the Main class, like I said above, simply call TeamMember.show(). You do not need to create an instance.
If you change your teamList to public instead of private your Main class will be able to access the variable. When you make something private in Java you're basically making that instance variable accessible only through the class that it's instantiated in. If you want the variable to be visible to other classes for reference you should make it public
Since the assignment calls for it, you're going to need to define a getter and setter for your 'teamList' variable.
public void setArray(ArrayList newTeamList){
teamList = newTeamList;
}
public ArrayList getArray(){
return teamList;
}
This'll allow you to access the private variable through the methods

Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1 [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
Pre Edit: The problem is when I mark it as static, so
public static int printMenuGetSelection()
it gives me the message
This Static method cannot hide the instance method from AMenu
I'm writing a Java program that reads files and gives the user multiple options for displaying things about the file. I'm currently writing a menu interface that implements an actual Interface and makes the program easier to use. However, I'm getting an exception when I try to call the menu method in my main method. The error is on the one active line in the main method where I call printMenuGetSelection(), and it says
Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1
How do I fix this bug? here is my program:
import java.util.*;
import java.io.*;
import java.text.*;
public class SpecialAssignment1 implements AMenu {
public static void main(String[] args) throws FileNotFoundException{
printMenuGetSelection();
/*System.out.println(RewardCustomer("transactions1.dat")); //CURRENTLY DISPLAYING TOP 6, DOESN'T WORK WITH TIES OR TOPN < lines
ProcessTransactionsFile("transactions2.dat", 52);*/
}
public int printMenuGetSelection() throws FileNotFoundException{
boolean runProgram = true;
Scanner s = new Scanner(System.in);
printStartMenu();
String startMenuSelection = s.next();
while(runProgram){
if(startMenuSelection.equals("1")){
startMenu1();
} else if(startMenuSelection.equals("2")){
startMenu2();
} else if(startMenuSelection.equals("3")){
startMenu3();
} else if(startMenuSelection.equals("4")){
startMenu4();
} else if(startMenuSelection.equals("5")){
runProgram = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
return 1;
}
public static void printStartMenu(){
System.out.println("**********************************************************");
System.out.println("Main Menu...");
System.out.println(" (1) RewardCustomers");
System.out.println(" (2) ProcessTransactionFiles");
System.out.println(" (3) TopCustomers");
System.out.println(" (4) QueryStatsFile");
System.out.println(" (5) Quit");
System.out.println(" Enter a valid selection: ");
}
public static void startMenu1() throws FileNotFoundException{
boolean runMenu1 = true;
while(runMenu1){
Scanner s = new Scanner(System.in);
System.out.println("Reward Customers Menu...");
System.out.println(" (1) Use transactions1.dat");
System.out.println(" (2) Use transactions2.dat");
System.out.println(" (3) Quit");
System.out.println(" Enter a valid selection: ");
String menu1Selection = s.next();
if(menu1Selection.equals("1")){
System.out.println(RewardCustomer("transactions1.dat"));
} else if(menu1Selection.equals("2")){
System.out.println(RewardCustomer("transactions2.dat"));
} else if(menu1Selection.equals("3")){
runMenu1 = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
}
public static void startMenu2(){
boolean runMenu2 = true;
while(runMenu2){
Scanner s = new Scanner(System.in);
System.out.println("Process Transaction Files Menu...");
System.out.println(" (1) Create transactions2.dat file");
System.out.println(" (2) Display transactions1.dat");
System.out.println(" (3) Display transactions2.dat");
System.out.println(" (4) Query transactions1.dat");
System.out.println(" (5) Query transactions2.dat");
System.out.println(" (6) Quit");
System.out.println(" Enter a valid selection: 4");
String menu2Selection = s.next();
if(menu2Selection.equals("1")){
}
}
}
public static void startMenu3(){
}
public static void startMenu4(){
}
I removed the code not pertaining to the question to make it easier to read, if it's needed I'll put it in. Also, here is the AMenu Interface. Please do not suggest any other changes to my program. If you think it's dumb to have the menu as an Implemented Interface, I 100% agree with you but that's the requirement. For reference, here is the AMenu Interface:
import java.io.FileNotFoundException;
public interface AMenu {
/**
* Prints a menu with selections and logic to return a valid selection.
* #return the selected item
*/
abstract int printMenuGetSelection() throws FileNotFoundException;
/**
* #return the numberOfMenuItems
*/
abstract int getNumberOfMenuItems();
}
Since printMenuGetSelection() is non static, you cannot call it from within the static method main() unless you create an instance of SpecialAssignment1 and call the method on that object.
you need to create an instance of your SpecialAssignment1 then call the method from that, as abstract requires an object.
As other people have said, you need to create an instance of SpecialAssignment1, then call printMenuSelection() on it. Part of what's making this confusing though is that you've stuck the main method inside the menu interface class. This whole thing would make more sense if you had a class SpecialAssignment1 with just the main method and a separate MenuGenerator class with all the menu generation stuff.

How to write a 3 class program and have the main class trigger methods in the other two

I have to write a program with 3 classes and lots of different methods.
I've written a simpler example to try and get an idea where I am going wrong
First class (music) is defining a music object with three data types. And should have a method to print the contents of an array.
the second class (musicArray) has all the data for the array and should build the array when the third class tells it too.
the third class(searchclass) has the main method it should tell the second class to make the array then with user input search the array for songs that match the rating.
import java.util.Arrays;
public class Music extends musicArray {
private String songTitle;
private double songLength;
private int rating;
static String everything;
public Music(String songTitle, double songLength, int rating) {
this.songTitle = songTitle;
this.songLength = songLength;
this.rating = rating;
}
public String getsongTitle()
{
return songTitle;
}
public double getsongLength()
{
return songLength;
}
public int rating()
{
return rating();
}
#Override
public String toString() {
return "music{"+ "songTitle= " + songTitle + ", songLength= "
+ songLength + ",rating=" + rating + '}';
}
public Music[] printsonglibrary(char[][] songDetails){
for (int count = 0; count <= 6; count++)
{
return System.out.println(songDetails[count]);
System.out.println(" ");
}
}
}
public class musicArray extends Searchclass{
static Music song1 = new Music ("achy breaky", 5.32, 10);
static Music song2 = new Music ("billy",1.2, 8 );
static Music song3 = new Music ("hello", 1.5, 9 );
static //Create array and make posistion 0 = song1
Music[] songDetails ={song1,song2,song3};
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
for(int count = 1; count <= songDetails.length; count++){
system out put for debugging
System.out.println(songDetails.length);
System.out.println(songDetails[count - 1]);}
}
/* public String songSeach(){
System.out.println("what rating of song do you want to search for?");
Scanner keyboard = new Scanner(System.in);
int searchValue = keyboard.nextInt();
if searchValue == rating in array use the printsonglibrary
method in the music class to print the array entry
*/
}
}
If I have the main method in the musicArray class I can print the array
So the question is how do I make the Songdetails array available in the seachclass?
You shouldn't directly expose any variables of one class to another. Instead consider giving the MusicArray class (note that by convention class names should begin with a capital letter) a public method, say public void printOutSongDetails() that would print out the contents of the array. Your main method can then call this method off of the MusicArray object that it has created. e.g.,
Edit 1
Also, the Music class should most definitely not extend the MusicArray class for there is no way that a Music object should behave like a MusicArray object. And on the same token, MusicArray should not extend the SearchClass.
Edit 2
Note that there are several other significant issues with your code that each one would prevent it from compiling, and this suggests that you should modify how you program (if you can't use an IDE). Try to compile early and often, and only add new code to the program after fixing any compilation errors so that the current code base compiles.
Edit 3
A small code example of what I was describing above.
class SearchClass {
public static void main(String[] args) {
MusicArray musicArray = new MusicArray();
musicArray.addMusic(new Music("Foobars Unit", 10.4, 5));
musicArray.addMusic(new Music("Spamalot", 11.0, 7));
//... etc ...
musicArray.printOutSongDetails();
}
}
Also, you'll probably not want those static Music variables but rather give MusicArray a method to add Music to its array, a public void addMusic method that accepts a Music object as a parameter.
One way is to make it public public Music[] songDetails ={song1,song2,song3};
A better way is to provide getter:
public Music[] getSongDetails() {
return songDetails;
}

Categories

Resources