Essentially, I’m trying to store user input in a multi dimensional array using for loops. If the user types in something which is not expected/wanted (e.g. less than 0), a warning message will be displayed and the loop should ideally ‘wait’ till it receives the next valid integer.
Currently, my code, as shown below, works OK but I’m wondering if there are any better/more optimized ways of doing this.
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
int number = input.nextInt();
if((input.nextInt() >= 0) {
array[row][column] = number;
} else {
System.out.println("Input must be > 0.");
column--;
}
}
Use a
do..whileloop to wait until the user inputs something valid. This is cleaner than modifying a loop counter.Even better would be to extract the reading code into it’s own function:
This version makes it very clear what you’re doing.