hasNextDouble(),我的程序停止而不会崩溃而没有循环

时间:2017-05-25 16:00:26

标签: java

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

这是有问题的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());

2 个答案:

答案 0 :(得分:0)

您在一行中声明您想要空格分隔的输入。我建议将输入作为String,然后将其拆分,如

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,直到您输入非Double值。

答案 1 :(得分:0)

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

此外,当输入不再是数字时,您需要一种摆脱循环的方法。

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