我是编程新手,如果对此有一个非常简单的答案,我深表歉意,但我似乎找不到任何实际答案。我在猜数字游戏中使用扫描仪对象进行用户输入。扫描仪在我的 main 方法中声明,并将在一个单独的其他方法中使用(但该方法将在所有地方调用)。
我试过将它声明为静态的,但 eclipse 对此有一个适合,不会运行。
public static void main(String[] args) {
int selection = 0;
Scanner dataIn = new Scanner(System.in);
Random generator = new Random();
boolean willContinue = true;
while (willContinue)
{
selection = GameList();
switch (selection){
case 1: willContinue = GuessNumber(); break;
case 2: willContinue = GuessYourNumber(); break;
case 3: willContinue = GuessCard(); break;
case 4: willContinue = false; break;
}
}
}
public static int DataTest(int selectionBound){
while (!dataIn.hasNextInt())
{
System.out.println("Please enter a valid value");
dataIn.nextLine();
}
int userSelection = dataIn.nextInt;
while (userSelection > selectionBound || userSelection < 1)
{
System.out.println("Please enter a valid value from 1 to " + selectionBound);
userSelection = dataIn.nextInt;
}
return userSelection;
}
最佳答案
您看到这些错误的原因是 dataIn
是 local main
方法,这意味着没有其他方法可以访问它,除非您明确地将扫描仪传递给该方法。
有两种解决方法:
- 将扫描器传递给
DataTest
方法,或者 - 在类里面使扫描器
静态
。
以下是您如何通过扫描仪:
public static int DataTest(int selectionBound, Scanner dataIn) ...
下面是如何使 Scanner
静态化:replace
Scanner dataIn = new Scanner(System.in);
在 main()
中
static Scanner dataIn = new Scanner(System.in);
在 main
方法之外。
关于java - 在方法中使用扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961823/