How to ask for input until 2 integers are received?

I need to validate that user inputs two integers and as such, I need to continue asking him for input until he provides both inputs that are integers. Not sure how to implement it, but I came up with something like that but now struggling to implement the part that checks if coord1 and coord2 get correct types. If not, it of course gives me the NumberFormatException:

  while (true) {
            System.out.print("Enter the coordinates: ");
            int coord1 = Integer.parseInt(scanner.next());
            int coord2 = Integer.parseInt(scanner.next());
            if (coord1 < 1 || coord1 > 3 || coord2 < 1 || coord2 > 3) {
                System.out.println("Coordinates should be from 1 to 3!");
                continue;
            } else if (cellOccupied(field, coord1, coord2)) {
                System.out.println("This cell is occupied! Choose another one!");
                continue;
            }
            break;
        }

Can I solve it without using try / catch, since I haven’t learned that yet, or is this the only way?

Thank you in advance and sorry, since I’m still learning Java syntax and ways of validation.

>Solution :

Instead of manually checking if the input is the right type, you could rely on the Scanner‘s methods hasNextInt() and nextInt().

The first one will check whether your input is an actual int and then you can proceed reading it with nextInt(). For further details about placing a nextLine() after reading a numeric type read the following question asked here on stack overflow.

Here I’ve also included your code in a sample main. I know yours was just a snippet with much more code around (I didn’t have the cellOccupied method, for example) but I’ve just pasted it like so for a minimal testing. Besides, I’ve also parameterized your use case. It was a bit odd and redundant to repeat the same code for reading the user input applying the same coordinate-logic.

public class Main {
    public static void main(String[] args) {
        int coord1 = 0, coord2 = 0;
        do {
            coord1 = readCoordinate("Enter first coordinate: ");
            coord2 = readCoordinate("Enter second coordinate: ");

            //Showing an error message if the coords refer to an occupied cell
            if (cellOccupied(field, coord1, coord2)) {
                System.out.println("This cell is occupied! Choose another one!");
            }
        } while (cellOccupied(field, coord1, coord2));
    }

    private static int readCoordinate(String message) {
        int coord;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print(message);
            if (scanner.hasNextInt()) {
                coord = scanner.nextInt();

                //getting rid of the new line character after reading the int
                scanner.nextLine();

                //Checking coordinate value
                if (coord < 1 || coord > 3) {
                    System.out.println("Coordinates should be from 1 to 3!");
                    continue;
                }
            } else {
                //assigning an undesired value (since your coords must be between 1 and 3
                coord = 0;

                //getting rid of the wrong user input
                scanner.nextLine();

                //Showing an error message
                System.out.println("Please enter an int value");

                //Skipping directly to the loop's condition
                continue;
            }

            break;
        }

        return coord;
    }
}

On a side note, avoid declaring fields in a loop.

Leave a Reply