编译器显示“错误:找不到符号”消息。我认为这与方法有关。

huangapple go评论67阅读模式
英文:

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);
}

huangapple
  • 本文由 发表于 2020年10月18日 08:56:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64408740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定