import java.util.Scanner;
public class ArrayGrades {
public static void main(String[] args) {
// Using try-with-resources to ensure scanner closes automatically
try (Scanner scan = new Scanner(System.in)) {
int studentsNumber = 0;
// Prompt user to enter the number of students
while (true) {
System.out.println("Please enter the number of students or 'bye' to quit:");
String input = scan.nextLine().trim();
// Check if user wants to exit
if (input.equalsIgnoreCase("bye")) {
System.out.println("Goodbye!");
return;
}
// Validate input is a number
try {
studentsNumber = Integer.parseInt(input);
if (studentsNumber > 0) {
break; // Valid input, exit loop
} else {
System.out.println("The number of students must be greater than 0.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input.");
}
}
// Initialize the array to store student scores
int[] scores = new int[studentsNumber];
// Prompt user to enter students' scores
System.out.println("Please enter students' scores:");
for (int i = 0; i < scores.length; i++) {
while (true) {
System.out.print("Student " + (i + 1) + " score: ");
try {
scores[i] = scan.nextInt();
if (scores[i] >= 0) {
break; // Valid score, exit loop
} else {
System.out.println("Scores cannot be negative. Please enter a valid score.");
}
} catch (Exception e) {
System.out.println("Invalid input. Please enter an integer score.");
scan.next(); // Clear invalid input
}
}
}
// Find the maximum score
int maxScore = scores[0]; // Assume first score is the max
for (int i = 1; i < scores.length; i++) {
if (scores[i] > maxScore) {
maxScore = scores[i];
}
}
System.out.println("\nThe highest score is: " + maxScore);
// Assign grades based on the highest score
System.out.println("\nGrades for students:");
for (int i = 0; i < scores.length; i++) {
String grade;
if (scores[i] >= maxScore - 10) {
grade = "A";
} else if (scores[i] >= maxScore - 20) {
grade = "B";
} else if (scores[i] >= maxScore - 30) {
grade = "C";
} else {
grade = "D";
}
System.out.println("Student " + (i + 1) + ": Score = " + scores[i] + ", Grade = " + grade);
}
}
}
}