gpt4 book ai didi

java - 使用多个扫描仪失败 - Java

转载 作者:行者123 更新时间:2023-11-30 07:44:01 26 4
gpt4 key购买 nike

我对 Scanner 类有疑问。我有一些方法可以读取用户的某些输入,但是在调用第一个方法后,其他方法会崩溃(无法读取输入)。我搜索了解决方案,看起来添加“scanner.nextLine()”可以解决问题,但事实并非如此。

public class GameController {

private int numberOfPlayers = 2;

private Board board = new Board('.');
String players[] = new String[numberOfPlayers];
char playersMarkers[] = new char[numberOfPlayers];

public void getPlayersNames() {
Scanner input = new Scanner(System.in);

for (int i = 0; i < players.length; i++) {
System.out.print("Insert player " + (i + 1) + "'s name: ");
players[i] = input.nextLine();
}
input.nextLine(); // <- this one was suppose to solve the problem
input.close();
}


public static void main(String[] args) {

GameController gc = new GameController();
gc.getPlayersNames();

Scanner scanner = new Scanner(System.in);

int array[] = new int[5];
for (int i = 0; i < array.length; i++) {
if (scanner.hasNext()) {
array[i] = scanner.nextInt();
}
}

scanner.close();

for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}

输出:

Insert player 1's name: John
Insert player 2's name: George
1
0
0
0
0
0

最佳答案

您没有从 scanner 中获取任何内容(在 main 方法中),因为您已经关闭了 System.in(在关闭 时)输入,在 getPlayersNames 方法的末尾)。

您不应自行关闭 System.in,因为它会阻止将来尝试从此流中读取数据。

关于java - 使用多个扫描仪失败 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185640/

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