Edgars
Edgars

Reputation: 953

Checking if the input value is integer type java

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?

Upvotes: 1

Views: 31742

Answers (4)

KJTester
KJTester

Reputation: 407

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

Upvotes: 0

lkamal
lkamal

Reputation: 3938

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

Upvotes: 3

Simulant
Simulant

Reputation: 20102

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;
    }
  }
}

Upvotes: 1

ArturSkowronski
ArturSkowronski

Reputation: 1792

You can use parseInt and check exception:

public boolean parseWithFallback(String text) {
try {
  Integer.parseInt(text);
  return true;
} catch (NumberFormatException e) {
 return false;
 } 
}

Upvotes: 5

Related Questions