Saverio
Saverio

Reputation: 99

Java GPA Program Issue

My program for some reason is calculating the GPA average wrong. If I enter 4.0 three times, then it says the average GPA is 3.0 but should be 4.0. Can someone help me find the issue?

//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;

do
{
    String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
    gpa = Double.parseDouble(gpaEntry);

    if (gpa >= 3.5)
        counter2 ++;

    total += gpa;
        counter ++;
}
while (gpa != 0);

double average = (double) (total/counter);

JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);

Upvotes: 3

Views: 137

Answers (2)

jb.
jb.

Reputation: 10351

Let's walk through the code

  • gpa = 0
  • get user input (user enters '2')
  • now gpa = 2
  • total += 2
  • counter ++
  • while(gpa != 0) // nope, gpa is 2
  • loop back
  • get user input (user enters '0')
  • now gpa = 0
  • total += 0
  • counter ++ // oops!
  • while(gpa != 0) // yep, quit the loop

but it's too late, we already incremented counter, so our average calculation is wrong

Upvotes: 5

ikhaliq15
ikhaliq15

Reputation: 153

What is wrong is that if a user enters 0, then it runs the program and then exits.

Try this code (Sorry, I do not have an editor at the moment so you might have to fix some small thing).

//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;

String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);

while (gpa != 0) {
    if (gpa >= 3.5)
        counter2 ++;

    total += gpa;
    counter ++;

    gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
    gpa = Double.parseDouble(gpaEntry);
}

JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);

Comment if you have any more questions.

Upvotes: 0

Related Questions