Reputation: 17
I am trying to read data from edittext and store them in double variable but the problem is the data does not store in the variable to make it clear ,I have this snippet of code:
String RR=Editcredit1.getText().toString();
double w4;
try {
w4 = Double.parseDouble(RR);
} catch (NumberFormatException e) {
w4 = 3; // your default value
}
the above code I am trying to store the edittex value in the variable but it goes to the default value which is 3,if I change the code and make it like this
String RR=Editcredit1.getText().toString();
double w4;//=Double.parseDouble(Editcredit1.getText().toString());
try {
w4 = 0;
} catch (NumberFormatException e) {
w4 = 3; // your default value
}
It would choose 0 which is very confusing to me, can anyone help me with it cos I have been trying to resolve it for 3 days.
Upvotes: 1
Views: 45
Reputation: 51
Replace "," to "." in user input. If user enters 12,2 it will throw an error. And your catch statement setting default value. Just set your default value when you define your variable. And inform your user when an error occurs in catch statement. Check comments in the code
String RR=Editcredit1.getText().toString();
double w4=0;
//Set your default values at variable definition.
try {
w4 = Double.parseDouble(RR.replace(",","."));
//replace "," to "." for convert
} catch (NumberFormatException e) {
//there is an error, do not set any variables, warn user show error e.getMessage() or more user friendly, E.g."Please enter numeric value"
//maybe stop procedure with return; statement.
e.printStackTrace();//or print trace to console
}
Upvotes: 0
Reputation: 2128
when you call Double.parseDouble()
, it might throw an exception. For example, if RR has the value "123aef"
, this would not be parsed and an NumberFormatException
would be thrown.
However, if you set w4 = 0
as in the second case, no exception would be thrown since it is a legal statement.
Also, it might be the case that RR contains a whitespace character in it so this also might cause an exception to be thrown. Try to log the RR string value surrounded by some delimiters (as a quotation mark) just to verify that you have correct input
Hope this helps!
Upvotes: 1