Validating input using java.util.Scanner?

"YOU AND THE ART OF ONLINE DATING" is the only product on the market that will take you step-by-step through the process of online dating, provide you with the resources to help ensure success. Get it now!

Java.util. Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them.

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 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.

This code is working for negative numbers but not for alphabet – bhavna raghuvanshi Jun 17 '10 at 6:30 That's probably the best way yo go about it, depending on the input method, of course. – Nubsis Jun 17 '10 at 6:30 2 @bhavna: learn from the code and do the rest yourself. – polygenelubricants Jun 17 '10 at 6:31 1 @bhavna, please stop expecting others to do all your work.

Also, thanking someone from time to time wouldn't hurt either. – Bart Kiers Jun 17 '10 at 6:38.

You can check the ascii value for the characters and write your conditions.

Can you pls code it. – bhavna raghuvanshi Jun 17 '10 at 6:26.

One idea: try { int I = Integer. ParseInt(myString); if (i.

If you are parsing string data from the console or similar, the best way is to use regular expressions. Read more on that here: java.sun.com/developer/technicalArticles... 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; iIsLetter(input. CharAt(i))) { System.out.

Println("This string does not contain only letters!"); break; } } Good luck!

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions