java - 扫描仪被跳过

标签 java java.util.scanner

我正在尝试从用户那里获取 2 个整数。这是我的代码的相关部分:

 public void play() {

        int row=0,col=0;
        initializeboard();
        printboard();

        do {

            currentPlayer = players.remove();  //Returns currentPlayer
            System.out.println("Ok, "+ currentPlayer.getname() + ", Enter your Move: Row[1-3] & Column[1-3]");
            Scanner choice = new Scanner(System.in);
            if (choice.hasNext()) {

                row = choice.nextInt();
                col = choice.nextInt();
                while (row<1 || row>3 || col<1 || col>3 || board[row-1][col-1] != '-' ) {
                    System.out.println("Well, Move is not Valid or has already Been Selected, Try Again :/");
                    row = choice.nextInt();
                    col = choice.nextInt();
                }
                choice.close();
            }

            board[row][col] = currentPlayer.getsign(); //Places Sign in Game Board
            printboard();
            System.out.println();
            players.append(currentPlayer); //Inserts the Next Player
        } while(!win() && !isFull());
}

首先,它抛出NoSuchElementException,所以我使用了.hasNext()。现在,它只是跳过扫描仪并立即调用 printboard()

最佳答案

问题在于您正在使用同一流创建然后关闭多个 Scanner 对象。

Peter Lawrey 在 this post 中的回答解释了为什么不应从同一流创建多个 Scanner 对象。以下是答案的引用:

Once you close a stream it closes the underlying stream and you can't use it again. Only close System.in if you want to prevent it being used again.

最好的办法是在程序中创建一个 final Scanner 对象(每个流),然后在需要使用它时将其传递到方法中:

static final Scanner scan = new Scanner(System.in);

关于java - 扫描仪被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50845958/

相关文章:

java - Maven 部署文件目标 : Why does the first execution interfere with the second one?

java - 为什么我们不能使用扩展边界添加java泛型中的元素?

java - 我不明白这是如何决定什么是素数什么不是素数

java - 调用无效方法

java - 获取用户输入的日期并将其保存为java中的日期

java - 装箱拆箱问题

java - JAVA中的奇怪Bug

java - 使用 ASCII 行处理 Java IO 的最快方法

java - 我的程序在没有扫描字符串的情况下终止

java - 从控制台获取用户输入的正确方法