i've found this line of code got error if the input not an number
int sum = Integer.parseInt(request.getParameter("sum"));
the error message is
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "a"
root cause
java.lang.NumberFormatException: For input string: "a"
how to handle the input if the input is a string or null?
thanks
You should first make sure request parameter is not null and contains numbers only using:
if (request.getParameter("sum") != null &&
request.getParameter("sum").matches("^\\d+$"))
int sum = Integer.parseInt(request.getParameter("sum"));
Try:
int sum = 0;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch (NumberFormatException e) {
// sum = 0. If you needed to do anything else for invalid input
// put it here.
}
It really depends on what should be done if sum is not a number.
try{
int sum = Integer.parseInt(request.getParameter("sum"));
}
catch(Exception e)
{
//how do you want to handle it? like ask the user to re-enter the values
}
Just catch the exception and handle it accordingly:
int sum;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch {
//do something if invalid sum
}
Check manually (loop over the characters)
Catch the exception
Try this:
try {
sum = Integer.parseInt(request.getParameter("sum"));
} catch (NumberFormatException e) {
... // handle if the string isn't a number
} catch (NullPointerException e) {
... // handle if it's null
}
Check for null before Using Intefer.parseInt and also you can check whether input contains other than numeric value
Here's a different approach that doesn't involve throwing and catching exceptions:
String input = request.getParameter("sum");
// Validate the input using regex
if (input == null || !input.matches("^-?\\d{1,8}$")) {
// handle bad input, eg throw exception or whatever you like
}
int sum = Integer.parseInt(input);
Note that this regex doesn't allow numbers too large, and allows negative numbers
I see the org.apache.jasper.JasperException Which means this is in a JSP? If you're adding code like that to a JSP, you might want to reconsider what you're doing. Ideally, you should handle things like input validation in a controller of some sort, and then pass off results to a template of JSP for rendering.
There are many frameworks out there to help with this sort of thing, and in general they're worth using because your web application will benefit from all of the work that the framework authors have already done in the realm of security etc...
Pretty much any of the half a dozen code answers already posted will work for you though if you just want to hack it out.
Related
I have a JTextField object that a user can type in a number(or anything) into. I am trying to parse this textfield for a number and I do a validation check to see if the number is within a certain range (1-999).
String lowerLimit = this.lowerLimitTextField.getText().trim();
String upperLimit = this.upperLimitTextField.getText().trim();
if( Integer.parseInt(lowerLimit) < 1 || Integer.parseInt(upperLimit) > 999 )
{
return "The string must be in the range 0-999";
}
My issue is that, the user can specify any value into the textfield. When I try to input something like "61412356123125124", I get a NumberFormatException when parsing the string. What would be the simplest way to handle such a case? I do have a check that makes sure that the inputted string is all numbers, so thats fine.
I have tried changing the parseInt() into a parseLong() but I still get the same issue, since the number inputted is essentially unbounded. Can this be done with parsing the string (preferred), or is the simplest way to set some constraints on the JTextField itself?
Use NumberFormatto parse
import java.text.NumberFormat;
import java.text.ParseException;
public class MyVisitor {
public static void main(String[] args) throws ParseException {
System.out.println(NumberFormat.getNumberInstance().parse("61412356123125124"));
}
}
outputs
61412356123125124
Looks like you do not want to get the number, just check range (0-999). In this case just catch NumberFormatException and return same string:
try {
if( Integer.parseInt(lowerLimit) < 1 || Integer.parseInt(upperLimit) > 999 ) {
return "The string must be in the range 0-999";
}
} catch (NumberFormatException e) {
return "The string must be in the range 0-999";
//or more relevant message, like "Number to long" or something
}
The answer is that the Exception is your friend: It's telling you the number is too large... Put the error handling in the catch block or better yet declare throws NumberFormatException and catching calling block so that the method can be recalled
So you can use Integer.parseInt, Long.parseLong, or new BigInteger(String)... I would recommend Integer.parseInt in this case. Once you've got an int, you can do bounds checking. And if it's out of bounds, you might just want to throw an NumberFormatException :)
I have a menu which reads integers for input ,here is the method for the menu:
public int menu(String _menuHeader,String[] _menuItems) throws InvalidInputException {
int choice = 0;
do {
try {
scanner.nextLine();
System.out.println(_menuHeader);
for (int i = 0; i < _menuItems.length; i++) {
System.out.println(" " + (i + 1) + " " + _menuItems[i]);
}
choice = scanner.nextInt();
if (choice <= 0 || choice > _menuItems.length) {
throw new InvalidInputException();
}
} catch (Exception e) {
System.out.println("Enter valid input");
validInput = false;
} catch (InvalidInputException e) {
System.out.println("Please enter a choice between 1 and" + _menuItems.length);
validInput = false;
}
} while (!validInput);
}
Now I want to catch a exception when the input is out of bound of the allowed choices, i.e input 7 for choices 1 and 2,
For this I have tried using InvalidInputException, but this gives a an compile error as 'cannot find symbol InvalidInoutException' although I have imported 'import.java.Throwable/Exception;'
Do you have a custom exception class defined for your "InvalidInputException"?. If not please go through this post for creating custom exception classes.
How to define custom exception class in Java, the easiest way?
There is not such thing as InvalidInputException in java.lang. You will have to create your own custom exception, and name it as you wish.
Sorry to say this, but judging from your code you have poor knowledge of how the exception handling works in Java. If this is exception practice, then refactor your code accordingly. If not, don't use exceptions at all. You don't need them in this snippet of code.
I didn't look up the import, but the problem is that you catch Exception before InvalidInputException. Java uses the first matching catch to handle an exception, so if you catch a superclass in front of any of its subclasses, the subclass catches will never occur.
Reverse the order of your catches and you'll have better luck.
Edit: OK, I did look it up and Scanner.nextInt() doesn't throw that exception anyway. You probably want java.util.InputMismatchException, but check for yourself:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29
PS: This really isn't the best way to handle invalid input, by the way. The Scanner class has a hasNextInt() method to detect whether a valid integer is next in the input stream or not. As a rule, it's generally better to avoid throwing and catching exceptions if there's a sensible alternative. The Scanner hasNext* methods are specifically designed to give you those sensible alternatives.
I read in a menu choice and typing in any number but 2 & 5 work.
String choice = promptUser(choicePrompt);
try {
outputInfo(String.format("choice=...%s...",choice));
int c = Integer.parseInt(choice);
/* process it */
}catch (NumberFormatException e) {
outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}
public static void outputInfo(String msg)
{
System.out.printf("\t%s\n",msg);
}
Good output:
Enter Option: 1
choice=...1...
Bad Output:
Enter Option: 2
choice=...2...
choice=2
java.lang.NumberFormatException: For input string: ""
Update:
I've hard-coded "2" and it still fails!:
String choice = promptUser(choicePrompt);
try {
choice="2";
outputInfo(String.format("choice=...%s...",choice));
int c = Integer.parseInt(choice);
/* process it */
}catch (NumberFormatException e) {
outputInfo(String.format("choice=%s",choice));
outputInfo(e.toString());
}
Hard-coding "5" also fails but "1" works!!!
Any ideas gratefully received.
Simon
If I assume your promptUser() method to be something like:
static String promptUser() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
return reader.readLine();
}
catch(Exception ex) {
return null;
}
}
(without the parameter) then the program behaves as expected - certainly there's nothing in that code that treats 2 or 5 differently. If you're getting an empty string then are you sure your prompt user method is working correctly?
Either way, the code you've posted here is essentially correct. I would imagine there's something else wrong in your more fully complete program that doesn't manifest itself when you've reduced it down here; perhaps you're running into a case where a local variable is hiding a field for example and you're not using the value you think you are (but at this point, I'm just guessing.)
updated
Seems the promptUser method is returning an empty String "". check if choice is empty before calling
ParseInt method
Also you can add trim() to eliminate spaces before and after the input
if(choice!=null && !"".equals(choice))
int c = Integer.parseInt(choice.trim());
printStackTrace() is your friend.
Turns out the number format exception was further down (in the 'process it' code) and was not being caught down there.
It was data driven so didn't happen on other machines.
Thanks to every one for your support.
Simon
I've tried scouring Google and several sites such as this to find an answer to my question and I'm just not having any luck. I'm in a second-tier Java course in college, and I'm trying to figure out how to do input validation on a floating point number while using a try-catch block. The gist of the scenario is as such:
A driver will call the method promptForMotherHeight(), this method is supposed to pull in a user's entry as a floating point number. The issue is that with the try-catch block, if the Scanner detects a non-floating point number, it won't dump the data out of the scanner's buffer. This leads to an infinite loop. I've tinkered with adding a Scanner.next() inside my catch block, but any data entered after the first attempt will not validate properly (meaning that I can enter in something such as 5.55555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555 and it will accept this as a valid input).
Here's what I'm working with, code-wise (I've imported all the things I need to at the top of the class and motherHeight is a private float instance variable at the top of the class):
public void promptForMotherHeight()
{
String motherHeightPrompt = "Enter mother's height in inches: ";
String motherError1 = "Invalid entry. Must be positive.";
String motherError2 = "Invalid entry. Must be a decimal number.";
boolean valid = false;
do
{
System.out.print(motherHeightPrompt);
try
{
motherHeight = stdIn.nextFloat();
valid = true;
}
catch (InputMismatchException e)
{
System.out.println(motherError2);
stdIn.next();
}
} while(!valid);
}
Any pointers or hints as to how I can accomplish proper input validation would be much appreciated. Thanks
You could do the floating point number validation in the try-catch like this.
do {
System.out.print(motherHeightPrompt);
try {
motherHeight = Float.parseFloat(stdIn.nextLine()); // This will read the line and try to parse it to a floating value
valid = true;
} catch (NumberFormatException e) { // if it was not a valid float, you'll get this exception
System.out.println(motherError2);
// You need not have that extra stdIn.next()
// it loops again, prompting the user for another input
}
} while (!valid); // The loop ends when a valid float is got from the user
I've finished a simple program that converts a decimal number to binary (32bit). I would like to implement some type of error message should the user enter in an overflow number (anything over 2147483647). I tried a if_else , loop, but quickly found out I couldn't even do that. So I messed with taking the input as a string, and then using some things like .valueOF() etc, and still can't seem to get around to the solution.
I don't see how I can compare any value to a >2147483648 if I can't store the value in the first place.
Here's the bare code I have for the getDecimal() method:
numberIn = scan.nextInt();
Edit:: After trying the try / catch method, running into a compile error of
"non-static method nextInt() cannot be referenced from a static context".
My code is below.
public void getDec()
{
System.out.println("\nPlease enter the number to wish to convert: ");
try{
numberIn = Scanner.nextInt();
}
catch (InputMismatchException e){
System.out.println("Invalid Input for a Decimal Value");
}
}
You can use Scanner.hasNextInt() method, which returns false, if the next token cannot be converted to an int. Then in the else block, you can read the input as string using Scanner.nextLine() and print it with an appropriate error message. Personally, I prefer this method :
if (scanner.hasNextInt()) {
a = scanner.nextInt();
} else {
// Can't read the input as int.
// Read it rather as String, and display the error message
String str = scanner.nextLine();
System.out.println(String.format("Invalid input: %s cannot be converted to an int.", str));
}
Another way to achieve this is of course, using try-catch block. Scanner#nextInt() method throws an InputMismatchException, when it can't convert the given input into an integer. So, you just need to handle InputMismatchException: -
try {
int a = scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid argument for an int");
}
I suggest you surround that statement with a try/catch block for NumberFormatException.
Like so:
try {
numberIn = Integer.valueOf(scan.next());
}catch(NumberFormatException ex) {
System.out.println("Could not parse integer or integer out of range!");
}
use exceptions.. whenever a number is entered more than its storing capacity then exception will be raised
Refer docs.oracle.com/javase/tutorial/essential/exceptions/
You can user hasNextInt() method to make sure that there is an integer ready to be read.
try this :
long num=(long)scan.nextLong();
if (num > Integer.MAX_VALUE){
print error.
}
else
int x=(int)num;
or try catch:
try{
int number=scan.nextInt()
}
}catch(Exception ex){
print the error
}