在方法中使用 Scanner

Mar*_*rus 3 java methods input

我是编程新手,所以如果对此有一个非常简单的答案,我深表歉意,但实际上我似乎找不到任何东西。我在猜数字游戏中使用扫描仪对象进行用户输入。扫描器是在我的 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;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 7

为什么你看到这些错误的原因是dataIn本地main方法,这意味着没有其他方法可以访问它,除非你明确地传递扫描仪那个方法。

有两种解决方法:

  • 将扫描器传递给DataTest方法,或
  • static在课堂上制作扫描仪。

以下是您可以通过扫描仪的方法:

public static int DataTest(int selectionBound, Scanner dataIn) ...
Run Code Online (Sandbox Code Playgroud)

以下是制作Scanner静态的方法:替换

Scanner dataIn = new Scanner(System.in);
Run Code Online (Sandbox Code Playgroud)

main()

static Scanner dataIn = new Scanner(System.in);
Run Code Online (Sandbox Code Playgroud)

main方法。