How to use Scanner to accept only valid int as input
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.
Related questions
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
How to validate that input to Scanner is an int?
What you are doing with sc.nextInt()
will only allow the user to enter an int or the program will throw an InputMismatchException (thus that part behaves the way you want). If you want to make sure the number isn't negative though, do this:
System.out.println("Enter your age here:");
while (!sc.hasNextInt()) {
System.out.println("Please enter an integer.");
sc.next();
}
int age = sc.nextInt();
if(age < 0) {
//do what you want if the number is negative
//if you're in a loop at this part of the program,
//you can use the continue keyword to jump back to the beginning of the loop and
//have the user input their age again.
//Just prompt them with a message like "invalid number entered try again" or something to that affect
}
else {
setAge(age);
//continue execution
}
I want to limit the integer input for the scanner in a range
You got your boundaries wrong! Obviously you meant:
if(input >= 1 && input <= 50)
break;
That's because an input is valid when being between 1 and 50. In that case you break out.
How Do I Safely Scan for Integer Input?
You should check whether or not the input can be parsed as an int before attempting to assign the input's value to an int. You should not be using an exception to determine whether or not the input is correct it is bad practice and should be avoided.
if(scanner.hasNextInt()){
option = scanner.nextInt();
}else{
System.out.printLn("your message");
}
This way you can check whether or not the input can be interpreted as an int and if so assign the value and if not display a message. Calling that method does not advance the scanner.
Check that scanner input IS ONLY an integer
To discard a line use
in.nextLine();
if you use
in.next();
it only reads one word/token. (By "word" I mean anything between whitespace)
I only want to accept an integer value as the input, not just if the line contains an integer.
int value;
while(true) {
// a number please.
try {
value = Integer.parseInt(in.nextLine());
if (value > 0)
break;
// not positive.
} catch (NumberFormatException e) {
// not an integer
}
}
Note: 0 is neither positive nor negative.
Integer validation using java.util.Scanner
It seems your solution is already quite simple. Here is a more minimalist version:
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
from https://stackoverflow.com/a/23839837/2746170
Though you would only be reducing lines of code while possibly also reducing readability.
Java check if a scan input is both a specific string and only three digits
That looks like a regular expression to me. You can use a Pattern
and Matcher
to test if the given order matches the Pattern
; does it start with F or S then B and then three digits. Like,
String[] arr = { "SB123", "FB124", "CBXXX", "FB1234" };
Pattern p = Pattern.compile("[SF]B\\d{3}");
for (String s : arr) {
Matcher m = p.matcher(s);
System.out.printf("%s %b%n", s, m.matches());
}
Outputs
SB123 true
FB124 true
CBXXX false
FB1234 false
Related Topics
Convert String to Double in Java
Is Java.Sql.Timestamp Timezone Specific
How to Find the User'S Home Directory in Java
Intersection and Union of Arraylists in Java
How Many Characters Can a Java String Have
How to Prevent Java.Lang.Numberformatexception: For Input String: "N/A"
Spring @Transactional Not Auto Rolling Back During Unchecked Exception
Why Should the Interface For a Java Class Be Preferred
Best Way to Parsedouble With Comma as Decimal Separator
Understanding Java'S Protected Modifier
How to Programmatically Determine Operating System in Java
@Requestparam VS @Pathvariable
Remove Elements from Collection While Iterating
In Java, Is the Result of the Addition of Two Chars an Int or a Char