我是编程新手,所以我很抱歉,如果有一个非常简单的答案,但我似乎找不到任何东西,实际上。我使用扫描器对象为用户输入猜你的数字游戏。扫描器在我的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
是本地 main
方法,这意味着没有其他方法可以访问它,除非您显式地将扫描仪传递给该方法。
有两种解决方法:
- 将扫描器传递给
DataTest
方法,或 - 使扫描器在班上成为
static
。
下面是你通过扫描仪的方法:
public static int DataTest(int selectionBound, Scanner dataIn) ...
以下是如何将Scanner
设置为静态的:Scanner dataIn = new Scanner(System.in);
在main()
中
static Scanner dataIn = new Scanner(System.in);
外部 main
方法
您不能访问在其他方法中声明的变量,即使是主方法。这些变量具有方法作用域,这意味着它们不存在于声明它们的方法之外。您可以通过将Scanner的声明移到所有方法之外来修复此问题。这样,它将享受类作用域,并且可以在主类中的任何地方使用。
class Main{
//this will be accessable from any point within class Main
private static Scanner dataIn = new Scanner(System.in);
public static void main(String[] args){ /*stuff*/ }
/*Other methods*/
}
作为java中的一般经验法则,变量不存在于声明它们的最小的{}
对之外(唯一的例外是定义类体的{}
):
void someMethod()
{
int i; //i does not exist outside of someMethod
i = 122;
while (i > 0)
{
char c; //c does not exist outside of the while loop
c = (char) i - 48;
if (c > 'A')
{
boolean upperCase = c > 90; //b does not exist outside of the if statement
}
}
{
short s; //s does not exist outside of this random pair of braces
}
}