在方法中使用扫描器

4

我刚学编程,如果问题很简单,请原谅,但是我似乎找不到真正的答案了。我正在使用一个扫描器对象来获取猜数字游戏中用户的输入。扫描器在我的主方法中声明,并将在另一个方法中使用(但该方法将被多次调用)。

我尝试将其声明为静态变量,但是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;
}

这实际上也解决了我在几个方法中使用的随机生成器的问题。 - Marshall Tigerus
2个回答

8
您看到这些错误的原因是因为dataIn本地的,即除非您明确将扫描仪传递给该方法,否则其他方法无法访问它。
有两种解决方法:
  • 将扫描仪传递给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方法之外的代码。


通过“在类中将扫描器设为静态”的说法,我想你是指“将扫描器设置为类的静态属性”。 - ddmps
@Pescis 我用例子扩展了答案。 - Sergey Kalinichenko

2

即使是在主方法中,您也无法访问在其他方法中声明的变量。这些变量具有方法作用域,意味着它们仅存在于声明它们的方法内部。您可以通过将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
      }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接