Home > other >  How to take only specified input from the user in java
How to take only specified input from the user in java

Time:09-17

I want to take input from the user in java and the inputs are in 0 and 1 only.If an user enters other than 0 and 1 the scannner must reject those numbers.Please resolve my isssue.

CodePudding user response:

Scanner class provides a method to check if input is Integer or not. If it's integer, check if it's either 0 or 1, else ask for input again

Scanner scanner = new Scanner(System.in);

        int num;
        do {
            System.out.print("Please enter input 0 or 1: ");
            while (!scanner.hasNextInt()) {
                String input = scanner.next();
                System.out.printf("Pls enter a valid number");
            }
            num = scanner.nextInt();
        } while (num < 0 || num > 1);

CodePudding user response:

Just another way (of many) this can be done:

Scanner userInput = new Scanner(System.in);
String num = "";
while (num.isEmpty()) {
    System.out.print("Please enter either 0 or 1 (q to quit): -> ");
    num = userInput.next();
    if (num.equalsIgnoreCase("q")) {
        System.out.println("Quiting - Bye Bye");
        return;
    }
    // Does the entry match either a 0 or a 1?
    if (!num.matches("[01]")) {
        // No...
        System.out.println("Invalid Entry! ("   num   ") Try again..." 
                             System.lineSeparator());
        num = "";   // Empty num so to re-loop.
    }
    // Yes, so exit loop with num containing the valid number of 0 or 1.
}
int number = Integer.parseInt(num); // Convert num to integer
System.out.println("The number you entered is:   "   number);    // Display number in Console
  • Related