Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Scanner to accept only valid int as input

I'm trying to make a small program more robust and I need some help with that.

Scanner kb = new Scanner(System.in); int num1; int num2 = 0;  System.out.print("Enter number 1: "); num1 = kb.nextInt();  while(num2 < num1) {     System.out.print("Enter number 2: ");     num2 = kb.nextInt(); } 
  1. Number 2 has to be greater than number 1

  2. Also I want the program to automatically check and ignore if the user enters a character instead of a number. Because right now when a user enters for example r instead of a number the program just exits.

like image 568
John Avatar asked May 26 '10 12:05

John


People also ask

How do you input an integer into a Scanner?

To read integers from console, use Scanner class. Scanner myInput = new Scanner( System.in ); Allow a use to add an integer using the nextInt() method. System.

How do I validate input when using Scanner?

To validate input the Scanner class provides some hasNextXXX() method that can be use to validate input. For example if we want to check whether the input is a valid integer we can use the hasNextInt() method.

How do you restrict input in Java?

This can be used like this: Integer i = (Integer)securedInput("Enter an integer:","int", 3); Double d = (Double)securedInput("Enter a double","double",4); String s = (String)securedInput("Enter a string","string",2);


2 Answers

Use Scanner.hasNextInt():

Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.

Here's a snippet to illustrate:

Scanner sc = new Scanner(System.in); System.out.print("Enter number 1: "); while (!sc.hasNextInt()) sc.next(); int num1 = sc.nextInt(); int num2; System.out.print("Enter number 2: "); do {     while (!sc.hasNextInt()) sc.next();     num2 = sc.nextInt(); } while (num2 < num1); System.out.println(num1 + " " + num2); 

You don't have to parseInt or worry about NumberFormatException. Note that since the hasNextXXX methods don't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.

Related questions

  • How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
like image 72
polygenelubricants Avatar answered Sep 22 '22 22:09

polygenelubricants


  1. the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
  2. not knowing what the kb object is, I'd read a String and then trying Integer.parseInt() and if you don't catch an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.
like image 44
Ledhund Avatar answered Sep 18 '22 22:09

Ledhund