hasNextDouble(),我的程序停止时不会崩溃,也不会循环 我的程序似乎停留在while循环的中间,没有崩溃,也没有无限循环。它只是停止了。 循环运行的输入量与用户提供的输入量相同,但不会在下一行代码上移动。 这是我第一次在java中使用hasNextDouble()。我做得对吗

hasNextDouble(),我的程序停止时不会崩溃,也不会循环 我的程序似乎停留在while循环的中间,没有崩溃,也没有无限循环。它只是停止了。 循环运行的输入量与用户提供的输入量相同,但不会在下一行代码上移动。 这是我第一次在java中使用hasNextDouble()。我做得对吗,java,Java,下面是有问题的while循环: System.out.print("Grades (separated by a space)"); while(in.hasNextDouble()) { student1.addGrade(in.nextDouble()); } 下面是我的代码: Scanner in = new Scanner(System.in); String input = ""; Student student1 = new Student();

下面是有问题的while循环:

System.out.print("Grades (separated by a space)");
while(in.hasNextDouble())
{
    student1.addGrade(in.nextDouble());
}
下面是我的代码:

    Scanner in = new Scanner(System.in);
    String input = "";
    Student student1 = new Student();
    GradeBook book = new GradeBook();

    // Sets the name of the first student
    System.out.print("Name: ");
    input = in.nextLine();
    student1.setNames(input);

    // Sets the grades of the first student
    System.out.print("Grades (separated by a space)");
    while(in.hasNextDouble()){
        student1.addGrade(in.nextDouble());
    }

    // Put the student into the GradeBook
    book.addStudent(student1);

    // Prints the report
    System.out.print(book.reportGrades());

您可以在一行中声明要使用空格分隔的输入。我建议将输入作为
字符串
,然后将其拆分,如

Scanner in = new Scanner(System.in);
String line = in.nextLine();
for(String s : line.split(" ")){
    student1.addGrade(Double.parseDouble(s)); //gives exception if value is not double
}
Scanner.hasNextDouble
将继续返回
true
,直到输入非双精度值。

使用hasNext()检查是否有任何内容,然后使用hasNextDouble()检查下一个输入是否可以转换为双精度。使用next()读取该值,但该值仍然是字符串,因此需要将其解析为double

此外,当输入不再是一个数字时,您需要一种通过中断退出循环的方法

while (in.hasNext()) {
    if (in.hasNextDouble()) {
        student1.add(Double.parseDouble(in.next()));
    } else {
        break;
    }
}

扫描仪不能假设只要System.in未关闭,就不会有更多的输入,这就是为什么
in.hasNextDouble()
需要等待任何输入或关闭流信号的原因。要退出循环,请提供非双精度值,如“finish”。感谢Pshema的解释,这很有意义。在序列末尾添加任何其他输入都有效。