Fouzi Medfouni
Fouzi Medfouni

Reputation: 25

While loop (check if the input from the keyboard is not an int, then keep asking until an int will be inserted)

trying to check if the input from the keyboard is not an int, then keep asking until an int will be inserted. any suggestions?

this is my piece of code(the catch part if the user will insert anything but int in the input stream):

this is my try/catch block....any other way to make it work and short! thank you in advance

                //thinking about using : while(!myscanner.hasNextInt())

            try
            {
                myinput = myscanner.nextInt();
                while(myinput > MAXARRAY || myinput < 0 || (myinput != (int)myinput))
                {   
                    System.out.print("Size must be from 0 - 15. Please reenter: ");
                    myinput = myscanner.nextInt();
                }
            }catch(InputMismatchException e)
            {
                while(myinput > MAXARRAY || myinput < 0 || (myinput != (int)myinput))
                {
                System.out.println("Size must be from 0 - 15. Please reenter: ");
                myinput = myscanner.nextInt();
                }
            }

Upvotes: 0

Views: 232

Answers (2)

Ashok Prajapati
Ashok Prajapati

Reputation: 374

Below code can used to solve it using the regular expressions for desired input.

    BufferedReader dataInputReader = new BufferedReader(new InputStreamReader(System.in));
    String input = null;
    Integer number = null;
    //Below pattern says 0-15
    Pattern pattern = Pattern.compile("[0-9]|1[0-5]");
       while(input==null || !pattern.matcher(input).matches()){
           System.out.print("Enter number: ");
           input = dataInputReader.readLine();
           if(pattern.matcher(input).matches()){
               number = Integer.parseInt(input);
           }else{
               System.out.println("Size must be from 0 - 15. Please reenter: ");

           }

       }
       System.out.println("Input number is: "+number);

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30809

You can do it with single while loop, e.g.:

Scanner scanner = new Scanner(System.in);
while(true) {
    System.out.println("Enter an int value");
    if(scanner.hasNextInt()) {
        int token = scanner.nextInt();
        System.out.println(token);
        break;
    }else {
        scanner.nextLine();
        continue;
    }
}

Upvotes: 1

Related Questions