Home > Net >  How can I only allow input ranging from 1-9 while still adding values to the multidimensional array?
How can I only allow input ranging from 1-9 while still adding values to the multidimensional array?

Time:12-02

Scanner input = new Scanner(System.in);
        System.out.println("Enter values:");
        for (int i =0; i < 3 ;i  )
            for (int j = 0; j < 3; j  ) //WANT TO NOT ALLOW VALUES OUTSIDE 1-9
                square[i][j] = input.nextInt();

I tried using if else constructs but it messed with the array and the for loop

CodePudding user response:

To prevent users from entering values outside the range of 1-9, you can use a while loop and the hasNextInt method in the Scanner class to check if the user's input is an integer. You can then use an if statement to check if the integer is within the desired range (1-9 in this case), and if it is, you can add it to the array. Here's an example:

Scanner input = new Scanner(System.in);
System.out.println("Enter values:");
for (int i =0; i < 3 ;i  ) {
    for (int j = 0; j < 3; j  ) {
        int value = 0;
        while (!input.hasNextInt()) {
            // If the input is not an integer, print an error message and ask for input again
            System.out.println("Invalid input. Please enter an integer between 1 and 9:");
            input.next();
        }
        value = input.nextInt();
        // Check if the integer is within the desired range
        if (value >= 1 && value <= 9) {
            // Add the value to the array
            square[i][j] = value;
        } else {
            // If the integer is not within the desired range, print an error message and ask for input again
            System.out.println("Invalid input. Please enter an integer between 1 and 9:");
            j--;
        }
    }
}

Note that in the else clause of the if statement, we decrement the value of j by 1 so that the current iteration of the loop is repeated. This allows us to continue asking for input until the user enters a valid integer within the desired range.

  • Related