【发布时间】:2021-11-17 16:42:10
【问题描述】:
尝试创建一个小程序,它可以通过控制台接受输入,同时也可以通过它输出数据。我为它使用了一个循环,但每当我尝试添加向控制台输入信息的功能时,它就会把程序弄乱。
本质上代码是这样的
//outputting stuff to the console. All works fine
if(scanner.hasNext() && scanner.nextLine() != null){
String input = scanner.nextLine();
}
这包含在循环中,用于输出内容的位也可以这样做。问题是,每当我添加有关扫描仪的位时,循环就会停止循环。那么有什么方法可以阻止扫描仪停止输出循环的其余部分,或者基本上是一种方法可以使我不必按回车键来再次循环。
编辑:这是整个代码段,以便更好地诊断。 reader 是来自另一部分代码的 inputStream。
while (true){
String input = self.reader.nextLine();
Scanner in = new Scanner(System.in);
String[] subbed = input.split(" ");
switch (subbed[0].toLowerCase()) {
case "setid":
self.setPlayerID(Integer.parseInt(subbed[1]));
System.out.println("Player ID set to: " + self.playerID);
break;
case "server":
System.out.println(input.replaceAll(subbed[0] + " ", ""));
break;
}
if(in.hasNext()){
String out = in.nextLine();
}
}
【问题讨论】:
-
您可以添加您的扫描仪声明吗?
-
Scanner scanner = new Scanner(System.in) -
试试这个:if(scanner.hasNext()){ String input =scanner.nextLine(); }
-
仍然挂起输入而不是继续。在提交至少 1 个字符之前不会继续。这让我非常难过。