#Exceptions
1 messages ยท Page 1 of 1 (latest)
Here is an AI assisted attempt to answer your question ๐ค. Maybe it helps! In any case, a human is on the way ๐. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
calculating the average score for each course. However, I am running into an issue with handling exceptions when the user inputs a non-integer value for the number of courses or number of tests.
To handle this issue, you can use a try-catch block to catch exceptions that occur when parsing user input. For example, you can use a try block to attempt to parse the user input as an integer and catch any NumberFormatException that may occur if the input cannot be parsed as an integer.
Scanner scanner = new Scanner(System.in);
int numCourses = 0;
try {
System.out.println("Enter the number of courses: ");
numCourses = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
}
// Continue with your code using numCourses
By using try-catch blocks to handle exceptions, you can ensure that your code does not crash if the user enters invalid input. You can also provide appropriate error messages to guide the user on how to enter valid input.
U can create a method that takes in a prompt and returns a positive integer and handles the validation for int/positive
Then the main part of the program can just be java int numberOfCourses = getPositiveIntFromUser("How many courses are you taking");
And since u want it to run again, loop it
Until valid
So the try catch can just be in that helper method
ok im going to try and input it just about the catch in the code and see if i can get it to work.