[英]Java: while loop for user input not executing
Edit: the problem turned out to be caused by my closing System.in in a previous part of the program, thereby making it unusable later on. 编辑:问题原来是由我在程序的前一部分关闭System.in引起的,因此在以后无法使用。
I'm trying to create a loop for user input but it's not functional... 我正在尝试为用户输入创建一个循环,但是它不起作用...
Here's what I've got: 这是我得到的:
Scanner userkey = new Scanner(System.in);
System.out.println("Enter commands");
while(userkey.hasNext()){
if (userkey.next().equals("exit")){
System.out.println("EXIT!!!!");
break;
}
System.out.println("In while loop test");
}
I guess userkey.hasNext() is return false for some reason... 我猜出于某种原因userkey.hasNext()返回false ...
try this: 尝试这个:
import java.util.Scanner;
public class Snippet {
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null)
{
System.out.println(readString);
if(readString.equals(""))
System.out.println("Read Enter Key.");
if(scanner.hasNextLine())
readString = scanner.nextLine();
else
readString = null;
if(readString.equals("exit")){
System.out.println("EXIT");
break;
}
}
}
}
Even your code should work, but this is a more verbose version. 甚至您的代码也可以使用,但这是一个更详细的版本。
Try this code: 试试这个代码:
import java.util.Scanner;
public static void main(String[] args) {
// TODO code application logic here
Scanner userkey = new Scanner(System.in);
System.out.println("Enter commands");
do {
if (userkey.next().equals("exit")) {
System.out.println("EXIT!!!!");
break;
}
System.out.println("In while loop test");
}while(userkey.hasNext());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.