gpt4 book ai didi

java - 初学者java编程if-else语句低效代码

转载 作者:行者123 更新时间:2023-12-01 17:16:47 25 4
gpt4 key购买 nike

我的代码是正确的,但它看起来太大了。我想知道它是否可以更有效并且变量更少。您有任何提示吗?谢谢

示例输出

输入三个分数:87 42 94

最低分数是:42
无最低分的平均分是:90.5
等级为:A

<code>
import java.util.Scanner;
public class GradeAverager
{

public static void main(String[] args)
{
int score1,score2,score3;
double average,average_no_lowest;

Scanner keyboard = new Scanner(System.in);
System.out.print("Enter three scores: ");
score1 = keyboard.nextInt();
score2 = keyboard.nextInt();
score3 = keyboard.nextInt();

average = (score1 + score2 + score3) / 3.0;

System.out.println();
System.out.println("The average is: " + average);


if (score1 < score2 && score1 < score3)
System.out.println("The lowest score was:" + score1);
else if (score2 < score1 && score2 < score3)
System.out.println("The lowest score was:" + score2);
else if (score3 < score1 && score3 < score2)
System.out.println("The lowest score was:" + score3);



if (score1 < score2 && score1 < score3){
average_no_lowest = (score2 + score3)/2.0;
System.out.println("The average without the lowest score is: " + average_no_lowest);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
else if (score2 < score1 && score2 < score3){
average_no_lowest = (score1 + score3)/2.0;
System.out.println("The average without the lowest score is: " + average_no_lowest);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}
else if (score3 < score1 && score3 < score2){
average_no_lowest =(score1 + score3)/2.0;
System.out.println("The average without the lowest score is: " + (score1 + score3)/2.0);
if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}

}
}
</code>

最佳答案

您的代码部分如下

if(average_no_lowest > 90)
System.out.print('A');
else if(average_no_lowest < 90 && average_no_lowest > 80 )
System.out.print('B');
else if(average_no_lowest > 70 && average_no_lowest < 80)
System.out.print('C');
else
System.out.print('D');
}

重复3次。将其放入方法中。

在问题得到证实之前,不要担心性能问题。担心阅读和维护代码是否容易。

代码有 2 个受众 - 编译器和人类。人类比编译器更重要。

关于java - 初学者java编程if-else语句低效代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21473142/

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