java “找不到符号:变量输入”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6526022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"cannot find symbol: variable input" error
提问by Dennis
Here is the code where I'm having trouble:
这是我遇到问题的代码:
import java.util.*;
public class Game {
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSORS = 3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name = intro();
int numRounds = numRounds(name);
game(name, numRounds);
}
public static String intro() {
System.out.println("Welcome to Rock Paper Scissors. I, the computer, will be your opponent.");
System.out.print("Please type in your name and press return: ");
String name = input.nextLine();
return name;
}
public static int numRounds(String name) {
System.out.println("Welcome " + name + ".");
System.out.println("All right " + name + ". How many games would you like to play?");
System.out.print("Enter the number of rounds you want to play and press return: ");
int numRounds = input.nextInt();
return numRounds;
}
When I use the scanner to get the values for the user's name and number of rounds they'd like to play, I get the error. I just want to return these values for use in the main function.
当我使用扫描仪获取用户姓名和他们想要玩的回合数的值时,我收到错误消息。我只想返回这些值以在主函数中使用。
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Bozho
There is no input
variable in the two methods that you want it - pass it as a methhod argument:
在input
您想要的两种方法中没有变量 - 将其作为方法参数传递:
public static String intro(Scanner input) { .. }
public static int numRounds(String name, Scanner input) { .. }
...
...
String name = intro(input);
int numRounds = numRounds(name, input);
Apart from that, there is no game()
method - define it.
除此之外,没有任何game()
方法 - 定义它。
回答by Nanne
I'm a bit rusty, but I think this line:
我有点生疏,但我认为这一行:
String name = input.nextLine();
Tries to use the variable input
, but that's not in its scope: it cannot "reach" it, so its not an initialised variable.
尝试使用变量input
,但这不在它的范围内:它无法“到达”它,所以它不是一个初始化变量。
Either put this in that function:
要么把它放在那个函数中:
Scanner input = new Scanner(System.in);
Or make input
"global" by declaring it as a for instance public
.
或者input
通过将其声明为 example 来使其成为“全局” public
。
回答by JustinKSU
Your intro()
and numRounds()
methods are referencing input
which is not visible to it. Try passing it in as a variable.
您的intro()
和numRounds()
方法正在引用input
它不可见的引用。尝试将其作为变量传入。
回答by Owen
input
is declared inside the main()
method, so it doesn't exist outside that method. You should declare it as a class variable, outside the main()
method, so that intro()
has access to it.
input
在main()
方法内部声明,因此它不存在于该方法之外。您应该在main()
方法之外将其声明为类变量,以便可以intro()
访问它。