尽管使用了哨兵值,循环仍然不会结束

时间:2010-09-24 01:35:38

标签: java

这是我的教科书中的一个例子,我不能让它结束循环。

import java.util.Scanner;

public class Play {

    System.out.println("Enter scores for all students.");
    System.out.println("Enter a negative number after");
    System.out.println("you have entered all the scores.");

    Scanner keyboard = new Scanner(System.in);
    double max = keyboard.nextDouble();
    double min = max;
    double next = keyboard.nextDouble();
    while(next >= 0)
    {
        if(next > max)
            max = next;
        else if (next < min)
            min = next;
        next = keyboard.nextDouble();

    }
    System.out.println("The highest score is " + max);
    System.out.println("The lowest score is " + min);
}

3 个答案:

答案 0 :(得分:1)

我为你修好了演示(见下文)。

当他应该使用的时候,他正在使用。

该演示声明您使用负数退出循环(低于零)。

 public static void main(String[] args) {
    System.out.println("Student score entry demo:");
    System.out.println("NB: Enter a negative number to finish.\n");
    Scanner keyboard = new Scanner(System.in);
    double max = -1;
    double min = max;
    double score;
    do {
      System.out.println("Enter student score: ");
      score = keyboard.nextDouble();
      if (score > max) {
        max = score;
      } else if (min < 0 || score < min && score >= 0) {
        min = score;
      }
    } while (score >= 0);
    // Output results
    System.out.println("The highest score was: " + max);
    System.out.println("The lowest score was: " + min);
  }

<强>输出:

学生成绩入门演示:

注意:输入所有分数后输入一个负数。

输入学生成绩:
22

输入学生成绩:
33

输入学生成绩:
44

输入学生成绩:
55

输入学生成绩:
11

输入学生成绩: -3

得分最高的是:55.0 得分最低的是:11.0

答案 1 :(得分:0)

这是我的0.02美元。 逻辑在评论中解释。

public static void main(String[] args) {

// Print instructions
System.out.println("Enter scores for all students.");
System.out.println("Enter a negative number after");
System.out.println("you have entered all the scores.");

Scanner keyboard = new Scanner(System.in);

// Init min and max
// Any grade will be lower than the current min grade 
// (which is the higest possible value a double can hold),
// and higher than the current max grade.
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;

// Read first grade. Allow the user to terminate the loop
// without entering grades
double next = keyboard.nextDouble();
while(next >= 0)
{
    if(next > max)
        max = next;

    // Removed else-if. This ensures the first grade is
    // initialized correctly
    if (next < min)
        min = next;
    next = keyboard.nextDouble();

}

// Make sure we got some grades
if (max == Double.MIN_VALUE && min == Double.MAX_VALUE) {
    System.out.println("No scores entered. Your students are lazy.");
} else {
    System.out.println("The highest score is " + max);
    System.out.println("The lowest score is " + min);
}

}

尝试输入-1作为唯一等级,并输入等级列表-1,看看你得到了什么。

答案 2 :(得分:-1)

您的情况为next >= 0,应为next > 0。您是否应该输入负值来完成输入值?