#Exceptions

1 messages ยท Page 1 of 1 (latest)

remote scarabBOT
#

<@&987246399047479336> please have a look, thanks.

#

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>.

#
TJ-Bot
So I am trying to run a code that asks the user to input the number of courses they are taking. Then the user inputers how many tests each course has in each course and then it moves on to ask the user for their grades on test. So the code works already bu

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.

devout shore
#

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");

leaden oak
#

ah ok thank you

#

that makes sense

devout shore
#

And since u want it to run again, loop it

#

Until valid

#

So the try catch can just be in that helper method

leaden oak
#

ok im going to try and input it just about the catch in the code and see if i can get it to work.