gpt4 book ai didi

java - 扫描仪被跳过

转载 作者:行者123 更新时间:2023-12-01 19:52:29 25 4
gpt4 key购买 nike

我正在尝试从用户那里获取 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com