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?

Community
  • 1
  • 1
Edgars
  • 913
  • 1
  • 19
  • 53
  • Can we get the exact error message? (and if possible a small, complete example that still shows your problem) – Dennis Meng Nov 05 '13 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? – Henry Nov 05 '13 at 18:14
  • @Dennis Meng I am sorry guys, but I can't recreate the error. Is there way to find previus compiling errors ? – Edgars Nov 05 '13 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. – Dennis Meng Nov 05 '13 at 18:28

4 Answers4

5

You can use parseInt and check exception:

public boolean parseWithFallback(String text) {
try {
  Integer.parseInt(text);
  return true;
} catch (NumberFormatException e) {
 return false;
 } 
}
ArturSkowronski
  • 1,722
  • 13
  • 17
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);
}
lkamal
  • 3,788
  • 1
  • 20
  • 34
  • @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 – Edgars Nov 05 '13 at 20:05
  • @Ikamal Is there any ideas, because I tried to change n variable location , but no succes ;( – Edgars Nov 05 '13 at 20:22
  • @EdgarsRozenfelds Updated the code to allow access to the user input outside the while loop using a new variable named `userInput`. – lkamal Nov 05 '13 at 20:46
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;
    }
  }
}
Simulant
  • 19,190
  • 8
  • 63
  • 98
  • 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. – Edgars Nov 05 '13 at 18:31
  • put your scanner in an other while loop repeating until your get your correct Integer. – Simulant Nov 05 '13 at 19:10
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

Julian Kolodzey
  • 359
  • 3
  • 9