gpt4 book ai didi

java - 有没有更简单的方法来执行此 if 语句?

转载 作者:行者123 更新时间:2023-12-01 22:26:18 25 4
gpt4 key购买 nike

我正在开发一个java程序,它接受输入的成绩,给出输入的总数和平均值,但是我无法弄清楚如何执行当前输入的最高成绩我正在使用大量嵌套的else if语句,但必须有一种简单的方法来做到这一点,而不是键入 100 个 else if 语句(这里是我的代码)。我在 else if 语句开始的地方放置了一条注释,以确定最高等级

//Jonathan Towell
//This program will take grade inputs and then display the amount of A's B's C's D's and F's
import javax.swing.JOptionPane;


public class Grades
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "Welcome to Jonathan's Gradebook");
int A = 0, B = 0, C = 0, D = 0, F = 0;
int totalGrades = 0, grade = 0, averageGrade = 0, highestGrade = 0;
while (grade >= 0)
{
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter one grade followed by the enter key\n when finished enter -1"));
if (grade <= 100 && grade >= 90)
{
A = A + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
if (grade == 100) // Determines highest grade
{
highestGrade = 100;
}
else if (grade == 99)
{
highestGrade = 99;
}
else if (grade == 98)
{
highestGrade = 98;
}
else if (grade == 97)
{
highestGrade = 97;
}
else if (grade == 96)
{
highestGrade = 96;
}
else if (grade == 95)
{
highestGrade = 95;
}
else if (grade == 94);
{
highestGrade = 94;
}
}

else if (grade > 100)
{
JOptionPane.showMessageDialog(null, "No extra credit for this assignment\n please enter a value less than 100");
}
else if (grade <= 89 && grade >= 80)
{
B = B + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
else if (grade <= 79 && grade >= 70)
{
C = C + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
else if (grade <= 69 && grade >= 60)
{
D = D + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
else if (grade <= 59 && grade >= 0)
{
F = F + 1;
totalGrades = totalGrades + 1;
averageGrade = averageGrade + grade;
}
}
averageGrade = (averageGrade / totalGrades);
JOptionPane.showMessageDialog(null, "Total number of grades entered was " + totalGrades + "\n The average grade was: " + averageGrade + " percent." + "\nA's: " + A + "\nB's: " + B + "\nC's: " + C + "\nD's: " + D + "\nF's: " + F + "\nThe highest grade earned was: " + highestGrade + " percent.");
System.exit(0);
}


}

最佳答案

为了使其更易于管理,您可以考虑使用具有多态性的工厂模式,并将所有等级括号(if、else-if)在它们自己的单独类中实现。

关于java - 有没有更简单的方法来执行此 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726058/

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