Reputation: 33
Greetings to fellow stack overflowers viewing this question, I am an amateur working on a boat racing game in Java, currently facing a problem where the try block in a for loop immediately iterates to the next loop even the input is invalid. The for loop consists of an input to initiate a dice throw and the dice throw function is in a separate class where it will throw an exception when the input is not "Y". The try block works perfectly when it is not in a for loop, but when placed in a for loop it automatically iterates the loop even the input is not valid.
for (int i = 0; i < boats.length; i++) {
try {
System.out.printf("BOAT %d TURN %n", i + 1);
System.out.println("Type Y to throw your dice!");
String diceThrow = input.nextLine();
boats[i].setPosition(newRiver.Flow(boats[i].getPosition(), newDice.diceThrow(diceThrow)));
System.out.println("boat position is at " + boats[i].getPosition());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
Upvotes: 0
Views: 79
Reputation: 131
I am assuming that the method in another class which is being used to simulate dice throw, is throwing IllegalArgumentException. And since you are handling it in the catch block, the for loop will not terminate, it will print the error and move on to the next iteration.
Upvotes: 2