我正在使用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)

当用户输入错误的东西时,它应该要求输入一次,然后再要求输入一次.

推荐答案

只需使用do-while(而不是while):

import java.util.Scanner;

public class HeloWrld {
    private static Scanner  scan = new Scanner(System.in);
    private static String  command;

    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) {
        do {
            System.out.println("Hello!!");
            answer();
        } while (!command.contains("Hello World!"));
        System.out.println("Good bye.");
    }
}

以上代码的样例运行的输出:

Hello!!
    > fjbejwkb
Hello!!
    > Hello World!
Good bye.

Java相关问答推荐

将偶数元素移动到数组的前面,同时保持相对顺序

具有额外列的Hibert多对多关系在添加关系时返回NonUniqueHealthExcellent

在Java中将Charsequence数组更改为String数组或List String<>

Listview—在Android Java中正确链接项目时出错

Spring boot:Bean和动态扩展器

使用@MappdSuperClass扩展ParentClass&Won t继承ParentClass属性

所有 case 一起输入时输出错误,而单独放置时输出正确

Spring @Value default无法计算表达式

格式中的特定回录键-值对

如何在Application.yaml中连接字符串?

尽管通过中断请求线程死亡,但线程仍将继续存在

SpringBoot:在条件{Variable}.isBlank/{Variable}.isEmpty不起作用的情况下进行路径变量验证

无法使用Freemarker从XML中读取重复的标记值

处理4.3问题:javax.xml.ind包不存在(&Q;).您可能在学习GitHub教程时遗漏了库.&Q

Android无法在Java代码中调用Kotlin代码,原因是在Companion中使用Kotlin枚举时

TinyDB问题,无法解析符号';上下文&

如何在Spring Security中设置一个任何人都可以打开的主页?

Intellij 2023 IDE:始终在顶部显示菜单栏

";home/runner/work/中没有文件...匹配到[**/pom.xml];Maven项目的构建过程中出现错误

java.lang.NoSuchMethodError:';org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream$Builder org.apache.poi-poi-ooxml-5.2.4