需要显示数字列表中的最高和最低等级

问题描述 投票:0回答:3

输入字符时,我需要输入等级列表并停止代码。然后将显示最高成绩和最低成绩。

我创建了一个while loop,但是当我运行代码时,它会不断循环并且不会停止。

public class MaxMinGrades{
  public static void main(String[] args){
    double maxGrade = Double.MAX_VALUE;
    double minGrade = Double.MIN_VALUE;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter as many student grades as you like. Enter a character to stop.");
    double grades = input.nextDouble();

    while(input.hasNextDouble()) {
      if (grades > maxGrade) {
        maxGrade = grades;
      }
      if (grades < minGrade) {
        minGrade = grades;
      }
    }
    System.out.println("The highest grade is: " + maxGrade);
    System.out.println("The lowest grade is: " + minGrade);
  }
}

我会输入:5066.8573.578.977 q。

输出为:最高等级为:78.9最低成绩是:50.0

java loops while-loop max min
3个回答
0
投票
public class MaxMinGrades{
  public static void main(String[] args){
    double maxGrade = 0.0;
            double minGrade = 100.0;
            Scanner input = new Scanner(System.in);
            System.out.println("Enter as many student grades as you like. Enter a character to stop.");


            while(input.hasNextDouble()) {
            double grades = input.nextDouble();
              if (grades > maxGrade) {
                maxGrade = grades;
              }
              if (minGrade > grades) {
                minGrade = grades;
              }
            }
            System.out.println("The highest grade is: " + maxGrade);
            System.out.println("The lowest grade is: " + minGrade);
  }
}

因此,while loop内部有中断条件。当某些更改时,将检查boolean条件。


0
投票

while循环中没有中断条件。扫描仪将继续监听输入。仅当输入非双字符时,循环才会退出。

您实际上也没有在每次迭代中获得下一个输入。您需要在循环内调用input.nextDouble()

如果您希望它自己退出,则需要添加一个中断条件。例如,您可以在输入一定数量后停止,例如:

int gradeCount = 0;
while(input.hasNextDouble() && gradeCount < 6) {
  grades = input.nextDouble();
  gradeCount += 1;

  // your logic here
}

0
投票

点对数

1。首次输入后,您需要为Min和Max分配该值。

2。变量等级应使用循环内的最新输入进行更新。

public class MaxMinGrades {
public static void main(String[] args){
    double maxGrade = Double.MAX_VALUE;
    double minGrade = Double.MIN_VALUE;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter as many student grades as you like. Enter a character to stop.");
    double grades = input.nextDouble();

    System.out.println("first entry="+grades);
    minGrade = maxGrade = grades;

    while(input.hasNextDouble()) {
        grades = input.nextDouble();
        if (grades > maxGrade) {
            maxGrade = grades;
        }
        if (grades < minGrade) {
            minGrade = grades;
        }
    }
    System.out.println("The highest grade is: " + maxGrade);
    System.out.println("The lowest grade is: " + minGrade);
}

}

© www.soinside.com 2019 - 2024. All rights reserved.