How can i handle it with scanner (java)?
Well your suggested source would not do what you want. Scanner breaks up input using a delimiter. The default delimiter is whitespace (spaces, tabs or newlines). Scanner.hasNext() simply tells you if there is a new whitespace delimted token. Scanner.next() simply returns that token. Note that none of these are effected by Scanner.findInLine(pattern) as all it does is search the current line for the provided pattern.
Maybe something like this (I have not tested this):
Scanner scanner = new Scanner("i:\\1.txt");
scanner.useDelimiter(";");
Pattern words = Pattern.compile("(RFID=|BLUID=|WifiID=)");//just separate patterns with |
while (scanner.hasNextLine()) {
key = scanner.findInLine(words);
while (key != null) {
String value = scanner.next();
if (key.equals("RFID=") {
System.out.print("RFID:" + value);
} //continue with else ifs for other keys
key = scanner.findInLine(words);
}
scanner.nextLine();
}
I would recommend you forget about using scanner and just use a BufferedReader and a couple of Pattern objects as that method is more flexible for what you want to do.
Java Scanner exception handling
Your program enters an infinite loop when an invalid input is encountered because nextDouble()
does not consume invalid tokens. So whatever token that caused the exception will stay there and keep causing an exception to be thrown the next time you try to read a double.
This can be solved by putting a nextLine()
or next()
call inside the catch
block to consume whatever input was causing the exception to be thrown, clearing the input stream and allowing the user to input something again.
How to handle empty scanner input strings in java?
You might want to use.
String furniID = reader.nextLine();
furniID = furniID.trim();
if(furniID.equals("")){
System.out.println("Empty Here. ");
}
As suggested in comments .readLine()
returns an empty string if you supply a blankline or simply hit enter.
The above regex expression will take care of empty string ""
or whitespaces
that user might enter.
edit 1
As suggested in comments regex could have been over-kill here. The string.trim() will take care of tabs, trailing-leading whitespaces and empty string.
How to handle users inputting invalid types into a scanner?
Short Answer
Use Integer.parseInt(input.nextLine())
in a try-catch block that looks for a NumberFormatException
.
Without Try-Catch
If you really must avoid the use of try-catch, then your idea of calling input.hasNextInt()
before attempting to parse the integer with input.nextInt()
will work.
int userInt = 0;
if (input.hasNextInt()) {
userInt = input.nextInt();
} else {
System.out.println("That wasn't a valid int.");
// Take whatever corrective action you want here.
}
Long Answer
If you have a UI for the calculator, then you can ensure that clicking specific buttons only sends valid values back to the calculation backend. However, since it looks like you are letting your users type in their values on the command line, there isn't a way to lock their keyboard into only being able to type valid numbers. As a result you have to test the validity of their input on your own.
Potential Enhancements
Also, when I'm trying to get a number from a user, I like to loop and keep asking them for a valid number instead of terminating the program. Consider something like this.
Scanner input = new Scanner(System.in);
int userInt = 0;
boolean userIntReceived = false;
while (!userIntReceived) {
try {
userInt = Integer.parseInt(input.nextLine());
userIntReceived = true;
} catch (NumberFormatException e) {
System.out.println("That wasn't a valid int. Please try again.")
}
}
// Now you have a valid int from the user.
input.close();
Cannot take input with Scanner
Just try to remove input.close();
statements
Related Topics
How to Dynamically Create a Test Suite in Junit 4
Getting Value of Public Static Final Field/Property of a Class in Java via Reflection
Jce Cannot Authenticate the Provider Bc in Java Swing Application
Java. Ignore Accents When Comparing Strings
Reading and Displaying Data from a .Txt File
How to Use Sqoop in Java Program
Spring 4 - Addresourcehandlers Not Resolving the Static Resources
Check Is a Point (X,Y) Is Between Two Points Drawn on a Straight Line
How to Find Out If "Debug Mode" Is Enabled
Tomcat Server Fails to Start the Server and Application in Sts
Gson.Tojson() Throws Stackoverflowerror
Soap Request to Webservice with Java
Noclassdeffounderror While Trying to Run My Jar with Java.Exe -Jar...What's Wrong