I am trying to use exceptions in my assignment to catch an error when a user input invalid entry.
I tried using the if else statement to catch but whenever running the program it will skipped pass my exception even when I input invalid entry. Do any of you have any idea where I am wrong in the code?
PS: please have mercy and go easy on me as I am still learning
private static void initArray() throws Exception {
while(true) {
System.out.print("\nPlease enter the name: ");
String name = scanner.nextLine();
if(!name.contains(" ")){
System.out.println("Please enter the coin:");
try {
int coinValue = scanner.nextInt();
if(coinValue>= 5){
if(coinValue % 5 != 1){
Change c = new Change(name, coinValue);
addChangeObject(c);
}else {
throw new Exception("invalid value);
}
}
}catch (Exception e){
c.setMessage(e.setMessage);
}
CodePudding user response:
You are throwing an exception at the appropriate condition, but then immediately catching that exception. After the catch
block the execution continues to prompt for another user.
There are a few ways to solve this:
You can have a
continue
statement in thecatch
block to continue with the next execution of the containingwhile(true)
loop, but that would require the user to re-enter a name before entering another coin value.The other option is to have another
while(true)
loop wrapping thetry-catch
block prompting for coins and abreak
statement if the conditions are met. Something like this:
while (true) {
System.out.println("Please enter the coin value for the person (multiple of 5):");
int coinValue = scanner.nextInt();
try {
if (coinValue >= 5 && coinValue <= 1000 && coinValue % 5 == 0) {
Change c = new Change(name, coinValue);
addChangeObject(c);
break;
} else {
throw new Exception("Value not within 5 to 1000 and not mutliples of 5");
}
} catch (Exception e) {
// catch logic asking the user to re-enter a coin value
System.out.error("Error: " e.getMessage());
}
}