我正在使用Java中的Scanner
类,我遇到了一个问题,我的程序将执行以下操作:
public static void answer() {
System.out.print("\t> ");
command = scan.nextLine(); // It needs to be able to read the full line to be able to capture spaces
}
public static void main(String[] args) {
while (!command.contains("Hello World!")) {
System.out.println("Hello!!");
answer();
}
}
但会打印出这样的内容:
Hello!!
> Hello!!
(user input)
因此,经过一些研究后,我决定将我的程序更改为如下所示:
public static void answer() {
scan.nextLine(); // new piece
System.out.print("\t> ");
command = scan.nextLine();
}
public static void main(String[] args) {
while (!command.contains("Hello World!")) {
System.out.println("Hello!!");
answer();
}
}
这导致了一个不同的问题.如果用户通过输入"fjbejwkb"而不是"Hello World!"来搞砸他们的输入,就会发生这种情况:
Hello!!
> fjbejwkb (user inputs wrong thing)
Hello!!
(user input)
> (user input)
如果我摆脱了增加的scan.nextLine()
,我又回到了原来的问题:"你好!!"被打印两次,但如果我离开它,每当我在第一次使用answer()
方法后使用它时,它将迫使用户键入两个内容.虽然第一个没有被阅读,但我相信这可能会导致一些混乱,我希望避免这样的情况.
我试过使用println
/\n
而不是scan.nextLine()
,但这在视觉上对我没有吸引力:
Hello!!
> (user input)
我也try 了command = scan.next()
而不是command = scan.nextLine()
,但这不能占用空间--对于我正在解决的问题,我需要这样做.
我想要的是
Hello!!
> fjbejwkb (user inputs wrong thing)
Hello!!
> (user input)
当用户输入错误的东西时,它应该要求输入一次,然后再要求输入一次.