Validating input using java.util.Scanner [duplicate] - java

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like:
It must be a non-negative number
It must be an alphabetical letter
... etc
What's the best way to do this?

Overview of Scanner.hasNextXXX methods
java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:
hasNext() - does it have any token at all?
hasNextLine() - does it have another line of input?
For Java primitives
hasNextInt() - does it have a token that can be parsed into an int?
Also available are hasNextDouble(), hasNextFloat(), hasNextByte(), hasNextShort(), hasNextLong(), and hasNextBoolean()
As bonus, there's also hasNextBigInteger() and hasNextBigDecimal()
The integral types also has overloads to specify radix (for e.g. hexadecimal)
Regular expression-based
hasNext(String pattern)
hasNext(Pattern pattern) is the Pattern.compile overload
Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.
Example 1: Validating positive ints
Here's a simple example of using hasNextInt() to validate positive int from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.
Related questions
How to use Scanner to accept only valid int as input
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Example 2: Multiple hasNextXXX on the same token
Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!
Here's an example of performing multiple hasNextXXX tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.
Example 3 : Validating vowels
Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.
API links
hasNext(String pattern) - Returns true if the next token matches the pattern constructed from the specified string.
java.util.regex.Pattern
Related questions
Reading a single char in Java
References
Java Tutorials/Essential Classes/Regular Expressions
regular-expressions.info/Character Classes
Example 4: Using two Scanner at once
Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.
Summary
Scanner provides a rich set of features, such as hasNextXXX methods for validation.
Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
Always remember that hasNextXXX does not advance the Scanner past any input.
Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.

Here's a minimalist way to do it.
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();

For checking Strings for letters you can use regular expressions for example:
someString.matches("[A-F]");
For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want.
Here
public int readInt(String prompt, int min, int max)
{
Scanner scan = new Scanner(System.in);
int number = 0;
//Run once and loop until the input is within the specified range.
do
{
//Print users message.
System.out.printf("\n%s > ", prompt);
//Prevent string input crashing the program.
while (!scan.hasNextInt())
{
System.out.printf("Input doesn't match specifications. Try again.");
System.out.printf("\n%s > ", prompt);
scan.next();
}
//Set the number.
number = scan.nextInt();
//If the number is outside range print an error message.
if (number < min || number > max)
System.out.printf("Input doesn't match specifications. Try again.");
} while (number < min || number > max);
return number;
}

One idea:
try {
int i = Integer.parseInt(myString);
if (i < 0) {
// Error, negative input
}
} catch (NumberFormatException e) {
// Error, not a number.
}
There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...

If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here:
http://java.sun.com/developer/technicalArticles/releases/1.4regex/
Otherwise, to parse an int from a string, try
Integer.parseInt(string). If the string is not a number, you will get an exception. Otherise you can then perform your checks on that value to make sure it is not negative.
String input;
int number;
try
{
number = Integer.parseInt(input);
if(number > 0)
{
System.out.println("You positive number is " + number);
}
} catch (NumberFormatException ex)
{
System.out.println("That is not a positive number!");
}
To get a character-only string, you would probably be better of looping over each character checking for digits, using for instance Character.isLetter(char).
String input
for(int i = 0; i<input.length(); i++)
{
if(!Character.isLetter(input.charAt(i)))
{
System.out.println("This string does not contain only letters!");
break;
}
}
Good luck!

what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input
Scanner s=new Scanner(System.in);
int a=s.nextInt();
while(a<0)
{
System.out.println("please provide non negative integer input ");
a=s.nextInt();
}
System.out.println("the non negative integer input is "+a);
Here, you need to take the character input first and check whether user gave character or not if not than again take the character input
char ch = s.findInLine(".").charAt(0);
while(!Charcter.isLetter(ch))
{
System.out.println("please provide a character input ");
ch=s.findInLine(".").charAt(0);
}
System.out.println("the character input is "+ch);

Related

Why do I get wrong mathematical results when using scanner class and delimiters for getting a double in Java?

I am writing a program where I have to get a user input, saved as a double. The user must be able to put it using both ',' and '.' as a delimiter - however they want. I tried using useDelimiter which works only partially - it does indeed accept both values (e.g 4.5 and 4,5) but when I later use the entered value in a mathematical equation, I get wrong results - it seems to round the user input down to the closest integer and as an effect no matter whether I enter, 4 or 4.5 or 4,5 or 4.8 etc., I get the same result, which is actually only true to 4.
Does anyone happen to know why it doesn't work?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
Thank you!
The useDelimiter method is for telling the Scanner what character will separate the numbers from each other. It's not for specifying what character will be the decimal point. So with your code, if the user enters either 4.5 or 4,5, the Scanner will see that as two separate inputs, 4 and 5.
Unfortunately, the Scanner doesn't have the facility to let you specify two different characters as decimal separators. The only thing you can really do is scan the two numbers separately, then join them together into a decimal number afterwards. You will want to scan them as String values, so that you don't lose any zeroes after the decimal point.
What useDelimiter() does is split the input on the specified delimiter.
As an example, if you have the input of 4,5, the following code will print "4".
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
If you also want to print the second part, after the ',', you need to add another line to get the next value, which would in this example print
"4
5":
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
System.out.println(sc.next())
In your code you can do it like this:
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
String firstPart = "0";
String secondPart = "0";
if (sc.hasNext()) {
firstPart = sc.next();
}
if (sc.hasNext()) {
secondPart = sc.next();
}
protectiveResistor = Double.parseDouble(firstPart + "." + secondPart)
}
// Rest of your code here
What this code does is split the input on whitespace, '.' and ','. For a floating point value you expect one part before the decimal point and one after it. Therefore, you expect the scanner to have split the input in two parts. These two parts are assigned to two variables, firstPart and secondPart. In the last step, the two parts are brought together with the '.' as decimal point, as expected by Java and parsed back into a variable of type Double.

What is memory buffer? And how different Scanner class methods operate on the probable issues of line breaks, white spaces etc.?

I am having trouble understanding how memory buffer works when I am working with Scanner class methods such as hasNextInt() hasNextDouble() etc. Considering the following code,
Scanner in = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive integer: ");
while (!in.hasNextInt()) {
System.out.println("It's not an integer!");
in.next();
}
number = in.nextInt();
} while (number <= 0);
System.out.println("Your number is " + number);
The output for some random values:
Enter a positive integer: five
It's not an integer!
-1
Enter a positive integer: 45
Your number is 45
What actually happens here? At line 1 when I enter five the nested while loop runs. What is the job of in.next()? After I enter five it says It's not an integer! But why doesn't it ask again: Enter a positive integer: ? Basically, I want the corresponding output to be like this:
Enter a positive integer: five
It's not an integer!
Enter a positive integer: -1
It's not a positive integer!
Enter a positive integer: 45
Your number is 45.
I would appreciate a brief and intuitive explanation how white spaces, line breaks are handled in input validation? And what is memory buffer? And how different methods of Scanner class like next(), nextLine(), nextInt(), nextDouble() etc. operate?
Also, how do I avoid repetition of It's not an integer!
Enter a positive number: five
It's not an integer!
one two three
It's not an integer!
It's not an integer!
It's not an integer!
10
Your number is 10
And finally, why many recommend try catch?
To start with, 0, -1, -66, 2352, +66, are all Integer values so you can't very well decide to designate them as otherwise. Your validation response should really be:
System.out.println("It's not a positive integer value!");
I personally never use those nextInt(), nextDouble(), etc methods unless I want blind validation. I just stick with a single loop, and utilize the nextLine() method along with the String#matches() method (with a small Regular Expression). I also don't really care for using a try/catch to solve a situation where I don't have to.
Scanner in = new Scanner(System.in);
int number = 0;
while (number < 1) {
System.out.print("Enter a positive integer (q to quit): ");
String str = in.nextLine();
if (!str.equals("") && String.valueOf(str.charAt(0)).equalsIgnoreCase("q")) {
System.exit(0);
}
// If a string representation of a positive Integer value
// is supplied (even if it's prefixed with the '+' character)
// then convert it to Integer.
if (str.matches("\\+?\\d+") && !str.equals("0")) {
number = Integer.parseInt(str);
}
// Otherwise...
else {
System.err.println(str + " is not considered a 'positive' integer value!");
}
}
System.out.println("Your number is " + number);
In this particular use-case, I actually find this more versatile but then, perhaps that's just me. It doesn't matter what is entered, you will always get a response of one form or another and, you have a quit option as well. To quit either the word quit or the letter q (in any letter case) can be supplied.
People like to utilize the try/catch in case a NumberFormatException is thrown by nextInt() because a white-space or any character other than a digit is supplied. This then allows the opportunity of displaying a message to console that an invalid input was supplied.
Because the Scanner class is passed System.in within its' constructor (in is an object of InputStream) it is a Stream mechanism and therefore contains a input (holding) buffer. When anything is typed to the Console Window it is place within the input buffer until the buffer is read by any one of the next...() methods.
Not all Scanner class methods like next(), nextInt(), nextDouble(), etc, completely utilize everything contained within the stream input buffer, for example, these methods do not consume whitespaces, tabs, and any newline characters when the ENTER key is hit. The nextLine() method however does consume everything within the input buffer.
This is exactly why when you have a prompt for a User to supply an Integer value (age) and you use the nextInt() method to get that data and then directly afterwords you prompt for a string like the User's name using the nextLine() method, you will notice that the nextLine() prompt is skipped over. This is because there is still a newline character within the input buffer that wasn't consumed by the nextInt() method and now forces the nextLine() method to consume it. That ENTER that was done in the previous nextInt() method is now passed into the nextLine() method thus giving the impression that the prompt was bypassed when in reality, it did receive a newline character (which in most cases is pretty much useless).
To overcome this particular situation the easiest thing to do is to consume the ENTER key newline character by adding scanner.nextLine(); directly after a int myVar = scanner.nextInt(); call. This then empties the input buffer before the String name = scanner.nextLine(); comes into play.

Java, How do I validate input when using scanner?

I am currently working on Java code. Basically, the int input works. However, if I type in a character, the whole system crashes. My question is as to what needs to be changed in the below code in order for the user to receive a message stating that only an int is the valid input, and to try again if they input a character.
do {
System.out.println("How many players would like to participate in this game?\t(2-4 players)");
numberOfPlayers = in.nextInt();
} while(in.hasNextInt());
numberOfPlayers = in.nextInt();
I personally prefer to use a while loop for this sort of thing rather than the do/while. Not that there is anything wrong with the do/while, I just feel it's more readable to use the while loop.
I agree with others here, accept String digits from the User instead of Integer. In my opinion it saves you other possible problems down the road and you have no need to purposely apply a try/catch mechanism should the User supply an invalid entry. It also allows you to easily apply a mechanism to quit the application which, again IMHO, should be made available to all Console app's.
You've got your answer for carrying out the task using a do/while loop but I would like to show you another way to do this sort of thing:
Scanner in = new Scanner(System.in);
String ls = System.lineSeparator();
int numberOfPlayers = 0;
String userInput = "";
while (userInput.equals("")) {
// The Prompt to User...
System.out.print("How many players would like to participate in this game?" + ls
+ "2 to 4 players only (q to quit): --> ");
userInput = in.nextLine();
// Did the User enter: q, quit (regardless of letter case)
if (userInput.toLowerCase().charAt(0) == 'q') {
// No, the User didn't...
System.out.println(ls + "Quiting Game - Bye Bye.");
System.exit(0); // Close (exit) the application.
}
/* Did the User supply a string representation of a numerical
digit consiting of either 2, 3, or 4. */
if (!userInput.matches("[234]")) {
// No, the User didn't...
System.out.println("Invalid input! You must supply a number from 2 to 4 "
+ "(inclusive)." + ls + "Try again..." + ls);
userInput = "";
continue; // Loop again.
}
// Convert numerical string digit to an Ingeger value.
numberOfPlayers = Integer.parseInt(userInput);
}
System.out.println(ls + "The Number of players you provided is: --> "
+ numberOfPlayers);
You will notice that the Scanner#nextLine() method is used to accept User input as a String. This now means that we need to validate the fact that a string representation of a Integer numerical digit (2 to 4 inclusive) was supplied by that User. To do this you will notice that I used the String#matches() method along with a small Regular Expression (RegEx) which consists of the following string: "[234]". What this does in conjunction with the String#matches() method is it checks to see if the string value in the userInput variable contains either a single "2", a single "3", or a single "4". Anything else other than any one of those three digits will display this message:
Invalid input! You must supply a number from 2 to 4 (inclusive).
Try again...
and, force the User make yet another entry.

How to check if the next 3 input is an int by using Scanner.hasNextInt() and loop only in java

How can I check if the next three input user is giving is an int value,
like let's say there is three variables,
var1
var2
var3
And I am taking input as,
Scanner sc = new Scanner (System.in);
var1 = sc.nextInt();
var2 = sc.nextInt();
var3 = sc.nextInt();
Now if I want to use while(sc.hasNextInt()) to determine if the next input is an int or not then it will only check if the next input for var1 is int or not and won't check for the other to variables, var2, var3. One thing can be done by using while loop with if (condition). For example,
Scanner sc = new Scanner (System.in);
while (sc.hasNextInt()) {
var1 = sc.nextInt();
if (sc.hasNextInt()) {
var2 = sc.nextInt();
if (sc.hasNextInt()) {
var3 = sc.nextInt();
}
}
}
But this looks lengthy and needs a lot to write. For similar issue I have seen for Language C there is a method for scanf() which can do the trick. For example,
while(scanf("%d %d %d", &var1, &var2 & var3) == 3) {
// Statements here
}
So my question is there any such features available in java's Scanner.hasNextInt or Scanner.hasNext("regex").
I have also tried sc.hasNext("[0-9]* [0-9]* [0-9]*") but didn't worked actually.
Thank you in advance.
hasNext(regex) tests only single token. Problem is that default delimiter is one-or-more-whitespaces so number number number can't be single token (delimiter - space - can't be part of it). So sc.hasNext("[0-9]* [0-9]* [0-9]*") each time will end up testing only single number. BTW in your pattern * should probably be + since each number should have at least one digit.
To let spaces be part of token we need to remove them from delimiter pattern. In other words we need to replace delimiter pattern with one which represents only line separators like \R (more info). This way if user will write data in one line (will use enter only after third number) that line would be seen as single token and can be tested by regex.
Later you will need to set delimiter back to one-or-more-whitespaces (\s+) because nextInt also works based on single token, so without it we would end up with trying to parse string like "1 2 3".
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\R");
System.out.print("Write 3 numbers (sepate them with space): ");
while(!sc.hasNext("\\d+ \\d+ \\d+")){
String line = sc.nextLine();//IMPORTANT! Consume incorrect values
System.out.println("This are not 3 numbers: "+line);
System.out.print("Try again: ");
}
//here we are sure that there are 3 numbers
sc.useDelimiter("\\s+");//nextInt can't properly parse "num num num", we need to set whitespaces as delimiter
int var1 = sc.nextInt();
int var2 = sc.nextInt();
int var3 = sc.nextInt();
System.out.println("var1=" + var1);
System.out.println("var2=" + var2);
System.out.println("var3=" + var3);
Possible problem with this solution is fact that \d+ will let user provide number of any length, which may be out of int range. If you want to accept only int take a look at Regex for a valid 32-bit signed integer. You can also use nextLong instead, since long has larger range, but still it has max value. To accept any integer, regardless of its length you can use nextBigInteger().
I tried with nextLine method and usage of Pattern. Regex is matching with 3 numbers which is separeted with space. So it can be like this i think ;
Scanner scanner = new Scanner(System.in);
Pattern p = Pattern.compile("[0-9]+\\s[0-9]+\\s[0-9]+$");
while(!p.matcher(scanner.nextLine()).find()){
System.out.println("Please write a 3 numbers which is separete with space");
}
System.out.println("Yes i got 3 numbers!");
I hope this helps you.

Is there another way to use hasNextInt() in Java without putting everything in the if-statement?

My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);

Categories