Reputation: 3
I need to write code that calculates the average of inputs (int) a user has entered. However, the problem is that I also have to allow the user to enter as many inputs as they want and stop when they enter a character(letter).
I can do this problem if there was a given limit I could use, but because the limit could be anything I am having trouble writing a formula that could calculate the average since the number of inputs could be different between any user.
import java.util.Scanner;
public class AvgGrades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter as many student grades as you like. Enter a character to stop.");
float total=0, avg;
int grades = input.nextInt();
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextInt();
total = total + grades[i];
}
input.close();
avg = total/grades.length;
System.out.println("Average student grade is "+avg);
}
}
The inputs are: 30.0 45.6 23.8 78.75 90 92 67.5 10.65 88 c The output should be: Enter as many student grades as you like. Enter a character to stop. Average student grade is: 58.477777777777774
My output is that the code just does not run.
Upvotes: 0
Views: 290
Reputation:
Here's a sketch of the process. I'll leave for you the details of turning that into a complete program.
float total = 0;
int count = 0;
while (scanner.hasNextFloat()) {
float num = scanner.nextFloat();
total += num;
count++;
}
float average = total / count;
You don't need to store the individual numbers.
Upvotes: 1