首页 > 解决方案 > 为什么在我第二次输入内容之前循环中断

问题描述

当我没有发送任何输入时,我想打破循环。但是,当我在第二次输入要输入的nameS内容时,尽管输入不是空的,但循环会自行中断。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(true) {
        System.out.print("Name: ");
        String nameS = sc.nextLine();
        if(nameS.isEmpty()) {
            break;
        }
        System.out.print("Student number: ");
        int numberS = sc.nextInt();
    } 
}

标签: java

解决方案


nextInt()next()方法不读回车。通常在数字之后,您必须按上述方法未准备好的回车键。避免这种情况的排序方法是保留 1 个额外的sc.nextLine()方法调用。它将读取并丢弃输入。

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.print("Name: ");
    String nameS = sc.nextLine();
    if (nameS.isEmpty()) {
        break;
    }
    System.out.print("Student number: ");
    int numberS = sc.nextInt();
    sc.nextLine();//you need to add this line in your code
    System.out.println(numberS);
}

推荐阅读