用户提示由于某种原因掉了一行?
User prompt is one line off for some reason?
我要求用户输入,但我希望它遵循 enter: 提示并在同一行。
我的代码生成此作为来自 'ok'
的输入结果
ok
enter: ok
ok
我希望用户输入在输入后开始:- 希望结果...
enter: ok
ok
这是我的代码:
private static Scanner u = new Scanner(System.in);
try{
while(u.hasNext() && !u.equals("exit")) {
System.out.printf("enter: ");
usrInput = u.next();
System.out.printf(usrInput + "\n");
System.out.println(findClosestMatch(usrInput.toLowerCase()));
}
} catch(NullPointerException e) {
System.out.println("Error - NullPointerException");
}
u.hasNext()
在提示之前阻止输入。这是不必要的,因为之后调用 u.next()
无论如何都会阻塞。并且您正在将实际的 Scanner
对象与 "exit" 进行比较,这永远不会是真的。试试这个:
while (true) {
System.out.print("enter: ");
if (!u.hasNext() || (usrInput = u.next()).equals("exit")) {
break;
}
System.out.println(usrInput);
System.out.println(findClosestMatch(usrInput.toLowerCase()));
}
我要求用户输入,但我希望它遵循 enter: 提示并在同一行。
我的代码生成此作为来自 'ok'
的输入结果ok
enter: ok
ok
我希望用户输入在输入后开始:- 希望结果...
enter: ok
ok
这是我的代码:
private static Scanner u = new Scanner(System.in);
try{
while(u.hasNext() && !u.equals("exit")) {
System.out.printf("enter: ");
usrInput = u.next();
System.out.printf(usrInput + "\n");
System.out.println(findClosestMatch(usrInput.toLowerCase()));
}
} catch(NullPointerException e) {
System.out.println("Error - NullPointerException");
}
u.hasNext()
在提示之前阻止输入。这是不必要的,因为之后调用 u.next()
无论如何都会阻塞。并且您正在将实际的 Scanner
对象与 "exit" 进行比较,这永远不会是真的。试试这个:
while (true) {
System.out.print("enter: ");
if (!u.hasNext() || (usrInput = u.next()).equals("exit")) {
break;
}
System.out.println(usrInput);
System.out.println(findClosestMatch(usrInput.toLowerCase()));
}