0

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());
    }
}
Han
  • 33
  • 6
  • try blocks don't iterate, it's the loop that iterates. Why would it stop iterating? if you want it to stop the moment the catch block is reached, just add a break; in there. – Stultuske Oct 25 '21 at 09:21
  • 1
    You probably don't want to use a for-loop here but rather something like `while(numBoatsEntered < maxBoats) { try { /*enter boat*/ numBoatsEntered++} catch(/*relevant exceptions*/) { /*print message and ignore input*/ }}`. And as Stultuske said, it's the loop that iterates, not the try-catch. You as the developer need to make sure that the conditions for the loop are maintained properly (i.e. decide when and how to alter the variables used in the condition - you also need to understand how the loop works for this) and when to `break;` out of the loop early. – Thomas Oct 25 '21 at 09:32
  • @Stultuske and Thomas(dunno why I can only tag one user) , Thank you so much for the reply! It was my lack of understanding of the try catch block and the fact that I had another while loop running that made me unable to detect this silly mistake. I understood where I messed up now. – Han Oct 25 '21 at 12:01

1 Answers1

2

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.

Tarun
  • 121
  • 7