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(); }
Number 2 has to be greater than number 1
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.
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.
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.
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);
Use Scanner.hasNextInt()
:
Returns
true
if the next token in this scanner's input can be interpreted as anint
value in the default radix using thenextInt()
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.
String
and then try
ing 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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With