我试图编写一个未加权的GPA计算器,但我遇到了一些问题。
import java.util.Scanner;
public class GPA
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many classes are you taking?");
int classes = keyboard.nextInt();
keyboard.nextLine();
int class1 = 0;
int gpa = 0;
for (int x = 0; x < classes; x++)
{
class1++;
System.out.println("What is your grade for class number " + class1);
String classGrade = keyboard.nextLine();
if (classGrade == "A" || classGrade == "a")
{
gpa += 4;
}
if (classGrade == "b" || classGrade == "B")
{
gpa += 3;
}
if (classGrade == "C" || classGrade == "c")
{
gpa+= 2;
}
if (classGrade == "D" || classGrade == "d")
{
gpa += 1;
}
if (classGrade == "F" || classGrade == "f")
{
gpa += 0;
}
}
double calculatedGpa = gpa / classes;
System.out.println("Your gpa is " + calculatedGpa);
}
}
输出正常到某一点。它询问我课程的数量,并询问每个班级的成绩。但是,最后,它每次都将GPA输出为0.0。我还是Java的新手;请问我的代码有什么问题?
答案 0 :(得分:1)
比较String
时出现问题。
您应该使用equals
代替==
:
if ("A".equals(classGrade) || "a".equals(classGrade))
{
gpa += 4;
}
...
如果NullPointerException
为空,我会在classGrade之前放置常量以避免classGrade
。