Joe Burkhart Joe Burkhart - 9 months ago 22
Java Question

Averaging numbers comes out incorect

I have tried looking this up on here and still haven't found the exact solution that I am looking for. The math keeps coming out incorrectly.

//Local Constants
int count = 0; //Used to track the number of grades entered by the user

//Local Variables
double currentGrade = 0; //User's current grade inputed
double numberGrades; //Total number of grades to be entered
double totalGrade = 0; //Total of all grades
double gradeAverage; //Average of all grades

//Main Function
//Ask the user for the amount of grades they would like to enter
System.out.print ("How many grades would you like to enter? ");
numberGrades = scan.nextInt();

//If the user asks to enter 0 numbers, output an error
while (numberGrades <= 0){
System.out.print ("Please enter a valid number! ");
numberGrades = scan.nextInt();
}
//Add the grades together as they are input by the user
while (count < numberGrades){
totalGrade += currentGrade;
System.out.print ("Please enter your next grade: ");
currentGrade = scan.nextInt();
count++;
}
//Calculate and output the average to the user
gradeAverage = (totalGrade / numberGrades);
System.out.print ("\n");
System.out.print ("The average of all grades is: " + gradeAverage);
}


}

Thought this was fixed, but when I run it I'm still getting the same issue. The example I tried was to enter 3 numbers, each was 50. The average ended up being 33.0. I've run the debugger and it keeps giving me errors once the first number is entered. count, totalGrade and currentGrade all show as errors. No clue how to fix it.

VHS VHS
Answer Source

You are doing the sum before getting the input. You should do it after that.

Replace your while loop with following change:

        while (count < numberGrades){

          System.out.print ("Please enter your next grade: ");
          currentGrade = scan.nextInt();
          totalGrade += currentGrade;
        count++;
        }