Skip to content

Instantly share code, notes, and snippets.

@TylerLH
Created March 5, 2014 00:08
Show Gist options
  • Save TylerLH/9358517 to your computer and use it in GitHub Desktop.
Save TylerLH/9358517 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class TestGrade {
public static void main(String [ ] args) {
int numberOfGrades;
int total = 0;
float average;
Scanner keyboard = new Scanner(System.in);
// Get the number of grades
do {
System.out.println("How many grades do you have to enter?\n");
while( !keyboard.hasNextInt() ) {
System.out.println("Grade count must be between 0 and 5. How many grades do you have to enter?\n");
keyboard.next();
}
numberOfGrades = keyboard.nextInt();
} while (numberOfGrades < 0 && numberOfGrades > 5);
// Get the grades total
for (int i=1; i<=numberOfGrades; i++) {
int grade;
do {
System.out.format("Enter grade %d: ", i);
while ( !keyboard.hasNextInt() ) {
System.out.println("\nInvalid grade. Try again: ");
keyboard.next();
}
grade = keyboard.nextInt();
} while (grade < 0);
total += grade;
}
// Average the grades
average = total/numberOfGrades;
// Print the average
System.out.format("Grade average is %f", average);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment