Reputation: 87
I'm trying to program an unweighted GPA calculator, but I've come across some issues.
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);
}
}
The output works correctly to a certain point. It asks me for the number of classes, and asks me for the grades of each class. However, at the end, it outputs the GPA as 0.0 every time. I'm still fairly new to Java; may I ask what is wrong with my code?
Upvotes: 1
Views: 122
Reputation: 56694
You have a problem when you compare the String
s.
You should use equals
instead of ==
:
if ("A".equals(classGrade) || "a".equals(classGrade))
{
gpa += 4;
}
...
I put the constant before classGrade to avoid a NullPointerException
if classGrade
is null.
See How do I compare strings in Java? .
Upvotes: 1