Java - Returning strings
I wish to return a string from a method object that is called by another method in another class. My problem is: when I attempt to assign the returned value to a String in the other class, it cannot find the method object within the class object.
Guessing Game = new Guessing();
This makes the object using the class Guessing.Java
else if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(Game.StartGame());
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
When I try retrieving the String from the StartGame method within the Guessing.Java class, it says it cannot fin开发者_JAVA百科d the class.
public String StartGame(double guess){
int round = 1;
int guesses = 3;
String correct = "correct";
if (guesses > 0){
if (guess == ans){
correct = "correct";
}else if ((guess == ans - 1)||(guess == ans + 1)){
correct = "hot";
guesses--;
}else if ((guess == ans - 2)||(guess == ans - 2)){
correct = "warm";
guesses--;
}else{
correct = "cold";
guesses--;
}
}else{
correct = "round";
}
return correct;
}
I have tried several different things and looked it up multiple times but nothing works, can anyone help?
First of all fix your code by using these Naming Conventions.
Change your code to this,
if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
String startGameStr = Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(startGameStr);
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
It is hard to tell what is causing the "class not found" exception with the details given.
But one thing I could see it : You are calling the method as:
label1.setText(Game.StartGame());
But the method expects a double
argument.
according to the first code segment there two overloaded methods in Guessing class
- StartGame(Double g)
- StartGame()
seems to be like you are calling the second method when you try to assing the returned string to that label which probably retuning emty string or since that method doesn't exist you get method not found exception.
精彩评论