gpt4 book ai didi

java - 为什么这段代码不能按预期工作?

转载 作者:行者123 更新时间:2023-12-01 06:30:43 28 4
gpt4 key购买 nike

我正在编写一个简单的方法,它将成绩作为用户的输入并计算平均绩点。这是我的代码:

public static double calculateGPA(){
Scanner in = new Scanner(System.in);

double totalGradePoints = 0; // total grade points
int numClasses = 0; // total classes completed
boolean doneInput = false; // returns true when use is done inputting grades

System.out.println("Enter all your grades (A,B,C,D,F) and enter 'done' if you are done entering your grades.");
while (!doneInput) {
String grade = in.next();

if (grade == "A") {
totalGradePoints += 4;
numClasses++;
} else if (grade == "B") {
totalGradePoints += 3;
numClasses++;
} else if(grade == "C") {
totalGradePoints += 2;
numClasses++;
} else if(grade == "D") {
totalGradePoints += 1;
numClasses++;
} else if(grade == "F") {
numClasses++;
} else {
doneInput = true;
} //end if - else-if - else statement
}//end while loop
double unwtGPA = (totalGradePoints/numClasses);
return unwtGPA;
}

当我测试该方法时,我只能输入一个成绩,并且没有任何变量递增,有人可以告诉我代码有什么问题吗?

最佳答案

问题在于使用 == 而不是 equals 进行字符串比较。 == 比较引用,它们不太可能相等。更改为

 if(grade.equals("A")){
totalGradePoints += 4;
numClasses++;
}else if(grade.equals("B")){ ...

它应该可以工作。请参阅this answer详细解释。

作为一个好的实践,建议始终使用静态字符串作为调用 equals 的对象以防止 NPE:

 if("A".equals(grade)){
totalGradePoints += 4;
numClasses++;
}else if("B".equals(grade)){ ...

如果您使用的是 Java 7,您还可以使用字符串执行 switch 语句(尽管如果 Grade 为 null,此语句将抛出 NPE):

switch(grade) {
case "A":
totalGradePoints += 2;
numClasses++;
break;
case "B":
...
}

最后,由于您只将一个字母转换为整数,因此最好的解决方案是将它们转换为 char,并且将 AD 之间的值转换为 char totalGradePoints += ('D' -grade.charAt(1)) + 1。因此,在我看来,沿着这些思路阅读的内容是最简单的:

while (true) {        
final String input = in.next();
if(input == null || input.isEmpty())
break;

final char grade = input.charAt(0);
if(grade >= 'A' && grade <= 'D') {
totalGradePoints += ('D' - grade) + 1;
} else if(grade == 'F') {
// no gradepoints for 'F'
} else {
break;
} //end if - else-if - else statement

++numClasses;
} //end while loop

关于java - 为什么这段代码不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21644741/

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