gpt4 book ai didi

java - 需要从数字列表中显示最高和最低成绩

转载 作者:行者123 更新时间:2023-12-01 22:08:29 27 4
gpt4 key购买 nike

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

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

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);
}
}

我会输入:50 66.85 73.5 78.9 77 q.

输出为:最高等级为:78.9最低等级为:50.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 循环内部就有了中断条件。当某些内容发生变化时,将检查 boolean 条件。

关于java - 需要从数字列表中显示最高和最低成绩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com