how to check if user input is a double? - java

In my JSP page, I let users input their dollar balance.
Then I catch this in servlet as: String input = req.getParameter("balance");
How do I check if input variable is double? I know how to use ParseDouble, but I don't want to catch the exception. Instead, I want to pass my own error message to JSP so that users can see it when they have typing error.
Can someone help me?

You may also create a function like this:
boolean isDouble(String input) {
try {
Double.parseDouble(input);
return true;
} catch (NumberFormatException e) {
//You can send the message which you want to show to your users here.
return false;
}
}

Related

I am trying to create a simple number guessing game

I ask the user to input a number until the user finds it.
I'm having trouble validating every input whether the user is typing in a number or anything else like char or string.
So basically I'm trying to prevent any mismatch exception error.
If you're writing code to take input as an integer, then it should come as an error or not move on if it doesn't have an int as an input.
If you're writing code to take a char or a string as an integer, then you should use Integer.parseInt() to convert your input to an int value.
Try to parse the text as a number, and if it fails, catch the failure and prompt the user to reenter the number.
Should be enough of a hint to get you going.
You can try to parse the String as a double and catch a NumberFormatException which will indicate that the input is not a valid number.
private static boolean isNumber(String s){
try{
Double.parseDouble(s);
return true;
} catch (NumberFormatException e){
return false;
}
}
If you want to not allow the String "NaN" to be accepted as a number, you can check if the String is equal to "NaN" before parsing it.
private static boolean isNumber(String s){
if(s.trim().equals("NaN")){
return false;
}
try{
Double.parseDouble(s);
return true;
} catch (NumberFormatException e){
return false;
}
}

while loop parsing Double.IsNaN improperly

Language: Java, IDE: eclipse mars
The program is supposed to prompt the user (using JOptionPane) for a positive value. I'm trying to catch the invalid entries. My while statement catches the negative numbers but not the strings. When a negative number is entered, the prompt is shown again, but when a string value is entered, the exception is caught and the program moves on (when it should re prompt the user).
Once a positive value has been entered, the program assigns it to a value in another class. (We're learning the MVC OOP design pattern).
Double.isNaN(Double.parseDouble(h)) ---> can anyone help me find what am I missing?
// prompt to get bandwidth from user
// check for validity
// if invalid, prompt again
try{
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
// loop until parsed string is a valid double
while (Double.isNaN(Double.parseDouble(h)) || Double.parseDouble(h) <=0) {
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
}
// h has been set to valid double, set it to bandwidth
model.setBandwidth(Double.parseDouble(h));
}catch(NumberFormatException|NullPointerException NFE){
System.err.println("Caught exception: " + NFE.getMessage());
}
This is because of how parseDouble() works.
Throws:
NumberFormatException - if the string does not contain a parsable double.
(See here)
So if the String is not a double parseDouble() will not return NaN but throw an exception, which means your catch clause will be called.
To solve this problem maybe use recursively algorithm which will call your method again if an exception is thrown.
As 4castle already stated, you need to move your try/catch block inside your while loop.
However, for validating user input you can basically stick to the following pattern:
public Foo getUserInput() {
Foo result;
do {
try {
String s = requestUserInput(); // something like Scanner.nextLine()
result = parseUserInput(s); // something like Double.parseDouble(String)
}
catch(Exception exc) {
// maybe you want to tell the user what's happened here, too
continue;
}
}
while(!isValid(result)); // something like (0 < result)
return result;
}

No conversion with Integer.ParseInt()

I have a problem that when I use Integer.parseInt in this context it doesn't convert my and somehow it even kick me out of loop so it dont't want to display for example System.out.print(1) after loop like everything was crashed but i have no error. Please help. That's a part of code which cause it. variable "input" is an Arrayl
for (int i=0;i<input.size();i++)
{
if(point>Integer.parseInt(input.get(i).split(":")[1]))
{
input.set(i,highScore + System.getProperty("line.separator"));
break;
}
}
Have you verified that input.get(i).split(":")[1] gives you exactly a string that only contains digits?
Integer.parseInt(String s) throws NumberFormatException, so you should execute that code inside a try/catch block like this:
for (int i=0;i<input.size();i++) {
try {
int parsedValue = Integer.parseInt(input.get(i).split(":")[1]);
// do whatever you want to do with parsedValue
}
catch(NumberFormatException e) {
System.out.print("I caught an error!, what i was trying to parse wasn't a number");
// or any other action you consideer that needs to be done when parseInt fails
}
}
There is only one explanation (if you are sure that no exception is thrown): the input is empty. :)

Continue Android app after checked exception is thrown

So I'm trying to parse an numeric input in my EditText box. I'm using Integer parse to parse input into int.
#Override
public void afterTextChanged(Editable s) {
int temp;
try{
temp=Integer.parseInt(s.toString());
//do something
}catch (NumberFormatException e){
temp=someOtherNumber;
}
}
I want to continue app even if user entered invalid number.
Is that possible?
Yes this is possible. Put only catch able code in try catch block. write your remaining code after above catch block.
NumberFormatException you should put when you are confident enough that
1.) Editable s, s is not null. // if not - use Exception class here
If that ius not the case, then catching more prcise exception ie. NumberFormatException is enough. you have already put a catch block, so exception will not be propagated, and you can still continue with your app.
basic Structure
try{
// do your stuff here 1
}catch(NumberFormatException nfe){
// do your stuff here 2
}
// do your stuff here 3
Either do your stuff at 1 and 2 both or just at 3
First check for Editable s it should not null then go further., If you want to catch any exception other than NumberformatException.
then change Catch(NumberFormatException e) to this catch (Exception e). If you have any query please let know.

java errorhandling: how to check for numberformatexceptions

I'm learning java and I'm trying to make a very simple application that does conversion of currency. You enter a rate, a direction (e.g : from euro to dollars or reverse) and an amount. the numbers valid non negative numbers.
So far I managed to make it so that the number can't be negative; now I need to throw an error if it's not a number.
I have following code:
public void setKoers(double koers)
throws NegativeValueException, NumberFormatException{
if (koers > 0 ) {
this.koers=koers;
} else {
throw new NegativeValueException("negative number");
}
}
and my main looks like
try {
cal.setKoers( Double.parseDouble(args[0]));
} catch(NegativeValueException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println( e.getMessage());
}
So how can I check if koers is a number or not.
I know I could put try and catch the error in my code, but I think this would go against the logic of where and how to deal with errors: in my main function I should catch any NumberFormatException
You do not need the NumberFormatException since Double.parseDouble() takes care of it for you. If it is not a proper number (in this case a Double) than the parseDouble() method will throw a NumberFormatException for you.
Here's how I would write it: (just take out the NumberFormatException)
public void setKoers(double koers) throws NegativeValueException {
if (koers > 0 ) {
this.koers=koers;
} else {
throw new NegativeValueException("negative number");
}
}
try{
cal.setKoers( Double.parseDouble(args[0]));
} catch(NegativeValueException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println( e.getMessage());
}
You will probably want to validate your input when the user tells the program to accept and process the input. In this portion of the code, you would convert the String to a number by parsing the input within a try/catch block, and then if an exception is encountered, notify the user of the error, prevent further processing, and perhaps clear any offending entry fields if present.

Categories

Resources