为什么此代码不能按预期工作?

问题描述:

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

I'm writing a simple method that takes grades as input from the user and calculates the Grade Point Average. Here is my code:

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

当我测试方法时,我只能输入一个等级而且没有如果变量增加,有人可以告诉我代码有什么问题吗?

When I tested the method, I was only able to input one grade and none of the variables incremented, can somebody tell me what's wrong with the code?

问题在于使用 == 而不是等于 == 比较不太可能相等的引用。更改为

The issue is with the string comparison using == instead of equals. == compares the references, which are very unlikely to be equal. Change to

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

它应该工作。有关详细说明,请参见此答案

and it should work. See this answer for a detailed explanation.

作为一种好的做法,建议始终使用静态字符串作为调用等于的对象以防止NPE:

As a good practice it is advisable to always use the static string as the object for calling equals on to prevent a NPE:

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

如果您使用的是Java 7,您还可以使用字符串执行 switch 语句(但如果成绩为null,则会抛出一个NPE):

If you are using Java 7, you can also do a switch statement with strings (though this one will throw an NPE if grade is null):

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

最后,由于您只将一个字母转换为整数,因此最佳解决方案是将它们转换为char以及 A D之间的值要做 totalGradePoints + =('D' - grade.charAt(1))+ 1 。因此,最简单的方法是阅读IMO:

And finally, since you are converting only one letter to an integer, to best solution is to convert them to char and for the values between A and D to do totalGradePoints += ('D' - grade.charAt(1)) + 1. So something along those lines would be simplest to read IMO:

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