1

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?

Harry You
  • 87
  • 2
  • 3
  • 11

1 Answers1

1

You have a problem when you compare the Strings.

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? .

Community
  • 1
  • 1
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 1
    Even better: use "A".equalsIgnoreCase(classGrade) instead of two conditions per if and you may want to use "else if" to convey, that all branches are mutually exclusive (and actually the code will be more performant) – Wolf Oct 29 '16 at 08:43