Purpose is to reduce the number of variables so instead of making many variables I want to do something like this:
Scanner scnr = new Scanner(System.in);
int number = 0;
scnr.nextInt();
if (((scnr.nextInt() >= 4) && (scnr.nextInt() <=10)))
{
number = scnr.nextInt();
}
Instead of
Scanner scnr = new Scanner(System.in);
int number = 0;
int validNum = 0;
number = scnr.nextInt();
if (((number >= 4) && (number <=10)))
{
validNum = number;
}
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.
Validate integer input using Scanner in Java We can use hasNextInt() method to check whether the input is integer and then get that using nextInt() method.
Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared.
You can use hasNext(String pattern)
import java.util.Scanner;
public class Test
{
public static void main ( String [ ] args )
{
System.out.print ( "Enter number: " );
Scanner scnr = new Scanner(System.in);
int number = 0;
//Check number within range 4-10
if (scnr.hasNext ( "^[4-9]|10" ))
{
number = scnr.nextInt();
System.out.println ( "Good Number: " + number );
}
else{
System.out.println ( "Is not number or not in range" );
}
}
}
Enter number: 3
Is not number or not in range
Enter number: 4
Good Number: 4
Enter number: 10
Good Number: 10
Enter number: 11
Is not number or not in range
nextInt()
will return new number on each call, so you can't do this
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