0

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.

4
  • 3
    Do you only want 1 input or do you mean for 3 separate inputs Commented Jul 13, 2016 at 15:28
  • 1
    every time you call sc.nextInt() it get another value. If you want to check the same value more than once, store it in a variable. Commented Jul 13, 2016 at 15:45
  • I just need 1 input from the user which is an integer between 1 and 301. Anything else they enter the program should prompt them to try again and enter a valid number this time. Commented Jul 13, 2016 at 17:39
  • edited to reflect current issue. Commented Jul 13, 2016 at 17:54

4 Answers 4

3

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: ");
    }
}

}

Sign up to request clarification or add additional context in comments.

9 Comments

where would I assign input? I can't do it within the while loop since i'd get an inputmismatchexception if the user enters a letter. After I check the condition, I need the user to give it another try but it still has to be an int and within that range. Could you give a more complete snippet?
@Chrine just encapsulate everything in an while (sc.hasNextInt()). Check the updated solution
thanks for going the extra mile, but unfortunately the update solution isn't working for me. If the user enters a letter, the program skips the entire while loop. I tried to encapsulate everything in a conditional to check for integer input, but same issue.
@Chrine That's my fault. Completed ignored the possibility of the user entering anything aside from a number. The new solution should work. Typically when you use scanner, you'd want to use TRY AND CATCH to ensure the user enters a valid input.
I'll give that a shot.
|
0

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.

Comments

0

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 (i.e 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.

3 Comments

Why are you using an int for flag?
code above fails immediately if user enters a letter instead of a number.
@Chrine check my answer now. I've edited it. It will surely work for you :)
-1

Use DO WHILE for result

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

OK ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.