javacalculator

Java GPA calculator


I have this code in my Main class. My issue is, when the GPA is calculated with total divided by classes. It does not give me the full number. EX if the total is 14 and the classes is 4 it is a 3.5, my code only gives me a 3.0. Does anyone know why, I greatly appreciate your help!

Scanner input = new Scanner(System.in);
    System.out.print("How many classes did you have?: ");
    int classes = input.nextInt();
    String grades = "";
    int total = 0;
    int dec;



    for (int j = 0; j < classes; j++) {

        Scanner inputters = new Scanner(System.in);
        System.out.print("What is your Grade?: ");
        grades = inputters.nextLine();


        if (grades.equals("A")){
        dec = 4; 
        total += dec;

    } else if (grades.equals("B")){
        dec = 3;
        total += dec;

    } else if (grades.equals("C")){
        dec = 2;
        total += dec;

    } else if (grades.equals("D")){
        dec = 1;
        total += dec;

    } else if (grades.equals("F")){
        dec = 0;
        total += dec;

    }

    }


    double GPA = total / classes;
    System.out.println(GPA);

    DecimalFormat formatter = new DecimalFormat("0.##");
    System.out.println( formatter.format(GPA));

Solution

  • It's because you are dividing int's by int's, which will never result in a floating point number. Change the type of total / classes to double (or cast them), and the GPA will be the number you expect.

    PS: Not that doubles are not really accurate, for example, 0.9 + 0.1 != 1.0. If you want to do 'proper' double calculations, use BigDecimal, and use the String constructors when using them.