1

I am requesting users input where he needs to write integers. I managed to create validation that checks if the value is higher than needed and so, with this code :

int n = sca.nextInt(); 
while (n<=0){
    System.err.println(error_1);
    n = sca.nextInt(); 
}                    

But now how to add check for strings, I found such solution How do I keep a Scanner from throwing exceptions when the wrong type is entered?

That uses hasNextInt() before actually reading the input, I tried to put this check inside while loop in the same place with n<=0 like this

while ( (n<=0)||(sca.hasNextInt() )) {
  ....
}

But it responded with error that variable n is not compatible with that method. So is there any way to overcome such thing?

4
  • Can we get the exact error message? (and if possible a small, complete example that still shows your problem) Commented Nov 5, 2013 at 18:13
  • "variable n is not compatible with that method": I am sure this was not the exact error message. What did you get? Commented Nov 5, 2013 at 18:14
  • @Dennis Meng I am sorry guys, but I can't recreate the error. Is there way to find previus compiling errors ? Commented Nov 5, 2013 at 18:26
  • Are you able to reproduce the error at all? If not, then there's not much help any of this is going to be able to do. Commented Nov 5, 2013 at 18:28

4 Answers 4

5

You can use parseInt and check exception:

public boolean parseWithFallback(String text) {
try {
  Integer.parseInt(text);
  return true;
} catch (NumberFormatException e) {
 return false;
 } 
}
Sign up to request clarification or add additional context in comments.

Comments

3

First invocation of nextInt() also can result in an exception, if you do not check whether the input is of int type.

Hope below will resolve your issue.

Scanner sca = new Scanner(System.in);

boolean incorrectInput = true;
int userInput = -1; // initialize as a negative  

while (incorrectInput) {

    if (sca.hasNextInt()) {
        int n = sca.nextInt();
        if (n < 0) {
            System.err.println("error_1");
        } else {
            // do anything else
            userInput = n;
            incorrectInput = false;
        }
    } else {
        sca.next();
    }
}

if (!incorrectInput) {
    System.out.println("UserInput = " + userInput);
}

3 Comments

@Ikamal IT is almost there, just need to resolve that the program methods that is below this code cannot access to n variable :(But anyway thanks for this
@Ikamal Is there any ideas, because I tried to change n variable location , but no succes ;(
@EdgarsRozenfelds Updated the code to allow access to the user input outside the while loop using a new variable named userInput.
1

You have to test if there is a next Int before trying to get the next Int.

boolean finished = false;
while(!finished){
  while(scan.hasNextInt()){
    int n = sca.nextInt(); 
    if(n <= 0){
      System.out.println("Error: Number smaller 0");
    } else {
      System.out.println("correct!");
      finished = true;
    }
  }
}

2 Comments

Looks great, but Where you got never got an Integer I need to call again input, so many times as needed to user insert correct data.
put your scanner in an other while loop repeating until your get your correct Integer.
0

You can request and validate user input as many times as need to do it right.

    private int readUserInput(String messageToUser) {
    System.out.print("Enter " + messageToUser);
    Scanner scan = new Scanner(System.in);
    boolean validInput = false;
    int res = 0;
    do {
      try {
        validInput = scan.hasNextInt();
        if (!validInput) {
          throw new NotIntUserInputException();
        }
        res = scan.nextInt();
        if (res < 1) {
          validInput = false;
          throw new NotPositiveIntUserInputException();
        }
      } catch (Exception e) {
        System.out.print(e.getMessage());
        scan.next();
      }
    } while (!validInput);
    return res;
  }

You have to create 2 classes NotIntUserInputException and NotPositiveIntUserInputException that are inheriting Exception class

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.