英文:
Compiler giving an "error: cannot find symbol" message. I think it has to do with the methods
问题
import java.util.Random;
public class GuessingGame {
    public static void newGame(int answer) {
        Random rand = new Random(answer);
        answer = rand.nextInt(51);
    }
    public static void main(String[] args) {
        int answer = 0;
        newGame(answer);
    }
}
英文:
I'm trying to have the main method call the newGame method but it's giving me an error.
error: cannot find symbol
newGame(answer);                                                                                                  
symbol: variable answer  
location: class GuessingGame
import java.util.Random;
public class GuessingGame {
   
public static newGame(int answer){
 
 Random rand = new Random(int answer);
 answer = rand.nextInt(51); 
 }     
public static void main (String [] args ){
   newGame(answer);   
 }
}
答案1
得分: 0
你发布的代码缺少一些部分,而且功能有限。我假设你想从 newGame 返回新的随机值(因此应该返回一个 int)。另外,最好将 Random 传递给你的方法(因为创建新的 Random 包括对其进行种子化,如果你在循环中迅速执行,可能会选择相同的种子)。因此,可能如下所示:
public static int newGame(Random rand) {
    return rand.nextInt(51);
}
然后你需要在 main 函数中保存 answer,并构造 Random。像这样:
public static void main(String[] args) {
    Random rand = new Random();
    int answer = newGame(rand);
}
英文:
Your posted code is missing a few things, and doesn't do much. I assume you want to return the new random value from newGame (and thus it should return an int). Also, it's better to pass the Random to your method (because creating a new Random involves seeding it, and if you do it quickly in a loop you can pick the same seed). So, that might look like
public static int newGame(Random rand) {
	return rand.nextInt(51);
}
Then you need to save the answer in main. And construct the Random. Like,
public static void main(String[] args) {
	Random rand = new Random();
	int answer = newGame(rand);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论