简体   繁体   中英

Using java scanner to check two conditions while taking user input

I need to user to enter an int between 1 and 301. I have this simple loop here to check for user input. I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input.

        while (!sc.hasNextInt()) {
            System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
            sc.next();
        }
        int numToCheck = sc.nextInt();
        // do stuff with numToCheck

This checks that the input is an int, but I can't seem to find a way to give the int input a bound. I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. How should I store the user input? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter).

Perhaps there is a better design to accomplish all this. Those are welcomed too.

Thanks in advance.

You're not saving the value of the of the input. So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition. EDIT: okay, I'll go the extra mile for you. See if this works.

***Accounted for the case where the user might enter a character instead of a number.

import java.util.*;
public class HelloWorld{

public static void main(String []args){
    Scanner sc = new Scanner(System.in);
    int input;
    while (true){
        if (sc.hasNextInt()){
             input = sc.nextInt(); // Assign the next integer to a variable
             if (input  <= 301  && input >= 1){ // Check if integer meets condition
                   break; // Condition met, break out of loop
            }
        }else{
              sc.next();
        }
        System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
    }
}

}

Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input.

Scanner in = new Scanner(System.in);
     int flag = 0,x=0;
     while(flag == 0){
         x = in.nextInt();
         if(x<1 || x>301){
             flag = 0;
             System.out.println("Invalid Input.");
         }
         else{
             flag = 1;
         }
     }

And if you want user to input more than 1 inputs (ie 3 here), than set a counter that increases with every valid input of the user, as following:

 Scanner in = new Scanner(System.in);
     int flag = 0,x=0,count = 1;
     while(flag == 0){
         x = in.nextInt();
         if(x<1 || x>301){
             flag = 0;
             System.out.println("Invalid Input.");
         }
         else{
             //executes when input is valid
             if(count == 3){
                 flag = 1;
             }
             count++;

         }
     }

Edit:

If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. And as you said you want only one input from user rather than 3 , you have to change exit condition. Change code as following:

Scanner in = new Scanner(System.in);
 int flag = 0,count = 1,x=0,flag1 = 0;
 String y;
 while(flag == 0){
     y = in.next();
     flag1 = 0;
     try{
         x = Integer.parseInt(y);
     }
     catch(NumberFormatException e){
         flag1 = 1;
         System.out.println("Invalid Input.");
     }
     if((x<1 || x>301)&&flag1 == 0){
         flag = 0;
         System.out.println("Invalid Input.");
     }
     else if(flag1 == 0){
         //executes when input is valid
         if(count == 1){   // put count == 3 if you want 3 inputs from user.
             flag = 1;
         }
         count++;
     }
 }

Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt() . If the String is not Integer , than it will throw the exception and we will continue the loop till the valid input is entered by the user.

I ran this code, to see if it would show a better performance than yours.

Scanner sc = new Scanner(System.in);

boolean valid = true;
do {
    if (!valid) {
        System.out.print("Invalid Input. ");
    }
    System.out.print("Please enter a valid number between 1 and 301: ");
    String input = sc.next();
    try {
        int value = Integer.parseInt(input);
        valid = (value >= 1 && value <= 301);
    } catch (NumberFormatException nfex) {
        valid = false;
    }
} while (!valid);

When the conversion to integer fails, the JVM hangs a little. I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design.

Use DO WHILE for result

  do{
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
  }while( x < 20 );

OK ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM