I had a simple question. I've been exploring basic input validation in java (Only accept integers or doubles etc.. from user). The code below Works great for simple applications but it did spark my curiosity; whenever you input a letter then follow it with a space then another letter, it displays the "Try again. Input numbers only " message twice.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input Number, BOi");
//Basic input validation. Only Accepts Integers.
while (!sc.hasNextInt()){
sc.next();//This Clears the Scanner for next input
System.out.println("Try again. Input numbers only.");
}
int userInput = sc.nextInt();
System.out.println("CONGRATS! YOU'VE ENTERED THE NUMBER: " +
userInput);
}
}
If I were to input
p p p
then the result would be
Try again. Input numbers only.
Try again. Input numbers only.
Try again. Input numbers only.
I would expect the result to just be Try again. Input numbers only. displayed once. Can anybody explain why this happens? I've heard the term "regex" thrown around but don't know if it's relevant. Thank you!
Its because next() does not consume the whole line. It only consumes the first word until space and the remaining words stays.
Thus when your loop will repeat as many words you have until it finds an int.
For example here you are giving P P P means 3 words hence thrice iteration
Thus you should use:
sc.nextLine() if you are expecting non integer and parse it
sc.nextInt(); and handle exception if someone inputs anything other
than int
Your problem is just a lack of knowledge of how Scanner really works.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
So when you enter p p p, Scanner.nextInt() will split p p p into p then p and then p. Thats why you get 3 times the same message.
Use nextLine() method to get the whole line and not "skip" any whitespace.
Related
I am curious how to get input data formatted from a user in java, for example if the user enters 1,2,3 how can I get these numbers in an array when the input look like this:
Scanner s = new Scanner();
String inputString = s.nextLine();
I can get a single number
Integer num = Integer.parseInt(inputString)
but I am unsure how handling multiple numbers would go
Well, you'd use... scanner. That's what it is for. However, out of the box a scanner assumes all inputs are separated by spaces. In your case, input is separated by a comma followed by/preceded by zero or more spaces.
You need to tell scanner this:
Scanner s = new Scanner(System.in);
s.useDelimiter("\\s*,\\s*");
s.nextInt(); // 1
s.nextInt(); // 2
s.nextInt(); // 3
The "\\s*,\\s*" think is a regexp; a bit of a weird concept. That's regexpese for 'any amount of spaces (even none), then a comma, then any amount of spaces'.
You could just use ", " too, that'll work, as long as your input looks precisely like that.
More generally if you have a fairly simple string you can use someString.split("\\s*,\\s*") - regexes are used here too. This returns a string array with everything between the commas:
String[] elems = "1, 2, 3".split("\\s*,\\s*");
for (String elem : elems) {
System.out.println(Integer.parseInt(elem));
}
> 1
> 2
> 3
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);
I am trying to get some integer inputs from user by using scanner.hasNextInt() method. It works just fine but I need to type a letter to let the program know that I'm done entering integers while I want the console to know that after I press the enter key after a single line.
For example, I type
(1
2
3
y
enter)
and the program works just fine but if I type
(1
2
3
enter
enter)
nothing happens, even if I keep pressing the enter key. This is the related part of my code, if you need to take a look at it.
public class Main {
static LinkedList linkedList =new LinkedList();
public static void main(String [] args){
System.out.println("enter integer numbers");
Scanner scanner=new Scanner(System.in);
while (scanner.hasNextInt()){
linkedList.append(scanner.nextInt());
}
print();
}
}
Three steps to understand it.
Scanner uses a delimiter to break the input into tokens, the default delimiter is \p{javaWhitespace}+. Try
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.delimiter());
\p{javaWhitespace} is equivalent to java.lang.Character.isWhitespace(), so \p{javaWhitespace}+ will matches multiple characters which isWhitespace.
A line break produced by key enter is a white space. When you enter multiple enters, they will be recognized as a delimiter, not a token.
You can use s single white space, so it will take the second enter as token:
scanner.useDelimiter("\\p{javaWhitespace}");
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);
I'm convinced this is a product of how the string.replaceAll() method works, but for some odd reason its making my loop run twice when you type anything with a space in it?
public class TestCode{
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
String input = "";
while(!input.equals("X")){
System.out.println("Prompt user for input");
input = scan.next().toUpperCase();
calculatePolynomial(input);
}
}
public static void calculatePolynomial(String input){
//Clean up entry removing spaces and extracting polynomial names
String calculation = input.replaceAll("\\s", "");
System.out.println(calculation);
}
}
The idea was to have the code run... printing out the message, prompting input. Then process the input and do some stuff. Repeat the process over and over until the sentinel value 'x' is entered.
But when you type input that contains a space it, for some reason, runs the loop as if each word was now separate input. So if you enter three words, it just runs the loop three times instead of once.
I just want the user's input to be without spaces and without a nightmare of logical errors.
When using a Scanner, by default, next() tokenizes the input by whitespace. So if the user enters two words separated by whitespace, your loop will run twice.
To get the entire input in the user's input line, try using the nextLine() method instead.