NumberFormatingExcepton if App is launched First Time - java

I have 4 TextViews. 3 of them display results of EditText input value in another activity, and it's saved with shared preferences.
The fourth TextView needs to display sum of that previous 3 TextViews.
I get the error: NumberFormatingException invalid double ""
This is my code:
// GETTING VALUES FOR FIRST 3 TEXTVIEWS
textViewRezultat1RMPotisakSKlupe.setText(settings.getString("benchSave", null));
textViewRezultat1RMCucanj.setText(settings.getString("squatSave", null));
textViewRezultat1RMMrtvoDizanje.setText(settings.getString("deadSave", null));
//LITTLE BIT OF MATH TO GET VALUE OF FOURTH
double prvo = Double.parseDouble(textViewRezultat1RMPotisakSKlupe.getText().toString());
double drugo = Double.parseDouble(textViewRezultat1RMCucanj.getText().toString());
double trece = Double.parseDouble(textViewRezultat1RMMrtvoDizanje.getText().toString());
double rezultat = 0;
rezultat = (prvo + drugo + trece);
textViewRezultat1RMUkupno.setText(Double.toString(rezultat));
That works like a charm.
The problem is, I get the error I mentioned above if the app is launched for the first time (with no stored data).
Can anyone help me solve it?

Actually the problem occurs when trying to parse a double from a string that is not representing a number or just simply null.
parseDouble
public static double parseDouble(String s)
throws NumberFormatException
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
Parameters:
s - the string to be parsed.
Returns: the double value represented by the
string argument.
Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable
double.
So you need to test both scenarios to be sure you are not in either of the faulty cases.
String prvoString = textViewRezultat1RMPotisakSKlupe.getText().toString();
Double prvo;
if(prvoString != null) { //shouldn't occur
try {
prvo = Double.parseDouble(prvoString);
} catch (NumberFormatException ex) { //inputs like "" or "banana"
//Tell the user he is entering invalid input
}
}
So why is this occuring when your app is running for the first time? The code that is parseDouble is executed when your view is loaded and trying to parse empty ("") strings.

Before doing double prvo = Double.parseDouble() always check whether your Strings are valid or not because if your String is empty, that is like "", you can't convert this to Double as its not a number.
So before every Double.parseDouble check like this -
if (!TextUtils.isEmpty(yourString))
Double.parseDouble(yourString);

Related

How do I fix the error of NumberFormatException everytime I run the program?

I have to create a love calculator object for my computer science class.
However, every time I compile and run the program I keep ending up with the error:
java.lang.NumberFormatException:
For input string: "70.78%" (in sun.misc.FloatingDecimal)
My code for the method:
public double calculate()
{
double value1;
double value2;
double sqrt1;
double sqrt2;
double relationship;
sqrt1 = Math.sqrt(name1.length());
sqrt2 = Math.sqrt(name2.length());
value1 = (Math.pow(name1.length(), 3)/(Math.random()+0.1))* sqrt1;
value2 = (Math.pow(name2.length(), 3)/(Math.random()+0.1))* sqrt2;
if(value1 > value2)
{
relationship = value2 / value1;
}
else
{
relationship = value1 / value2;
}
NumberFormat nf = NumberFormat.getPercentInstance();
nf.setMinimumFractionDigits(2);
return Double.parseDouble(nf.format(relationship));
}
I attempted to convert it to a float. I tried to separate it by declaring and initializing another double variable and returning that instead but they didn't work. I looked up solutions and most said to use a try and catch but I don't understand how that would work (since I just began the class and am a beginner).
How would I use a try and catch for this situation?
NumberFormat is meant to create a human readable string. 70.78% isn't a number. 70.78 is, but with the percent sign, it's a string. It seems like what you're trying to do is use the number formatting functionality to round the number. This question has some suggestions for how to properly round a number and keep it as a number.
To answer your other question, the proper way to use a try/catch would be like this:
double result;
try{
result = Double.parseDouble(nf.format(relationship));
}catch(NumberFormatException e){
e.printStackTrace();
result = 0.0;
}
return result;
But the only thing that will do is cause your program to not crash and you'll always get 0.0 returned from the calculate() method. Instead you need to fix the source of the exception.
As you see the exception stacktrace, the exception is caused by string 70.78%. This is because it has a symbol where Double.parseDouble() is expecting a string in format of double value representation like 70.78. If you are looking for an output like 70.78% and if the value is correct, you may return nf.format(relationship) and change your return type of calculate to String.
Update
The following values are valid to be parsed as double: "1.2", "1", ".2", "0.2", "1.2D", "1.", to say a valid number representation holdable by the datatype.

Parsing string to double/float throwing errors

I am extracting couple of values like 1234, 2456.00 etc from UI as string. When I try to parse this string to float, 1234 is becoming 1234.0 and when I tried to parse as double its throwing error. How can I solve this?
I am using selenium web driver and java. Below are few things I tried.
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
I think you mixed it up a bit when trying to figure out how to parse the numbers. So here is an overview:
// lets say you have two Strings, one with a simple int number and one floating point number
String anIntegerString = "1234";
String aDoubleString = "1234.123";
// you can parse the String with the integer value as double
double integerStringAsDoubleValue = Double.parseDouble(anIntegerString);
System.out.println("integer String as double value = " + integerStringAsDoubleValue);
// or you can parse the integer String as an int (of course)
int integerStringAsIntValue = Integer.parseInt(anIntegerString);
System.out.println("integer String as int value = " + integerStringAsIntValue);
// if you have a String with some sort of floating point number, you can parse it as double
double doubleStringAsDoubleValue = Double.parseDouble(aDoubleString);
System.out.println("double String as double value = " + doubleStringAsDoubleValue);
// but you will not be able to parse an int as double
int doubleStringAsIntegerValue = Integer.parseInt(aDoubleString); // this throws a NumberFormatException because you are trying to force a double into an int - and java won't assume how to handle the digits after the .
System.out.println("double String as int value = " + doubleStringAsIntegerValue);
This code would print out:
integer String as double value = 1234.0
integer String as int value = 1234
double String as double value = 1234.123
Exception in thread "main" java.lang.NumberFormatException: For input string: "1234.123"
Java will stop "parsing" the number right when it hits the . because an integer can never have a . and the same goes for any other non-numeric vales like "ABC", "123$", "one" ... A human may be able to read "123$" as a number, but Java won't make any assumptions on how to interpret the "$".
Furthermore: for float or double you can either provide a normal integer number or anything with a . somewhere, but no other character besides . is allowed (not even , or ; and not even a WHITESPACE)
EDIT:
If you have a number with "zeros" at the end, it may look nice and understandable for a human, but a computer doesn't need them, since the number is still mathematically correct when omitting the zeros.
e.g. "123.00" is the same as 123 or 123.000000
It is only a question of formatting the output when printing or displaying the number again (in which case the number will be casted back into a string). You can do it like this:
String numericString = "2456.00 "; // your double as a string
double doubleValue = Double.parseDouble(numericString); // parse the number as a real double
// Do stuff with the double value
String printDouble = new DecimalFormat("#.00").format(doubleValue); // force the double to have at least 2 digits after the .
System.out.println(printDouble); // will print "2456.00"
You can find an overview on DecimalFormat here.
For example the # means "this is a digit, but leading zeros are omitted" and 0 means "this is a digit and will not be omitted, even if zero"
hope this helps
Your first problem is that "SOQ" is not a number.
Second, if you want create a number using a String, you can use parseDouble and give in a value that does not have a decimal point. Like so:
Double.parseDouble("1");
If you have a value saved as a long you do not have to do any conversions to save it as a double. This will compile and print 10.0:
long l = 10l;
double d = l;
System.out.println(d);
Finally, please read this Asking a good question
The problem is you cannot parse non-numeric input as a Double.
For example:
Double.parseDouble("my text");
Double.parseDouble("alphanumeric1234");
Double.parseDouble("SOQ");
will cause errors.
but the following is valid:
Double.parseDouble("34");
Double.parseDouble("1234.00");
The number you want to parse into Double contains "," and space so you need first to get rid of them before you do the parsing
String str = "1234, 2456.00".replace(",", "").replace(" ", "");
double Val=Double.parseDouble(str);

How to convert string to double

double d=0.0;
for (String k : word.keySet()) {
System.out.println(k + "\t" + word.get(k));
d+=Double.valueOf(word.get(k));
d+=word.get(k);
word.get(k);
}
System.out.println("Value\t"+d);
The values are in hashmap. Incompatible type error occurs in 5th line.how to correct it?
The line d+=Double.valueOf(word.get(k)); will correctly add the Double value of word.get(k) to your double d, provided the String is parsable as Double.
The line after it, however, adds a String to a double, which will not compile.
The last line in your loop doesn't make any sense, you are invoking get without actually using the value.
You can use Double.parseDouble()
Eg:
String str="2.25";
double d=Double.parseDouble(str);
System.out.println(d);
You can convert String value to Double like this--
double latitu=Double.parseDouble("21.2186653");
If the error is in 5th line that's because you are trying to add whatever you have in the set word with double d. Java do not know what you have in the set word so you can type cast it if the word is a set of double. Otherwise you have to parse the double from what "word.get(k)" returns.
try d+=(double) word.get(k), if word is a set of double
or d+=double.valueOf(word.get(k)). if you have string in the set word.
In your 5th line of sample code, you are trying to add a string value with a double. that's why you are getting error
use
d += Double.parseDouble(word.get(k));
rather than
d+=word.get(k)

JSONObject getstring removes the zero from string

I'm trying to get numerical values that start with 0s from a JSONObject. The problem is the method converts the string into a double. Example:
JSONObject:
{
"LATITUDE1":41,
"LATITUDE2":06962
}
When I use
String lat2 = object.getString("LATITUDE2");
the String lat2 is displayed as 6962.0. How can I make it so that the string is displayed as it is in the json file (as 06962)?
I will then need to concatenate the two values and add a dot in between them to get a decimal number such as 41.06962 that's why I need to get the values as strings.
Thanks
If it's a string let it be a string:
{
"LATITUDE1":"41",
"LATITUDE2":"06962"
}

Using an input string in a textbox

I am trying to have the user input a number, and then that number is used to populate
a text field on a jform. However it keeps giving me errors. If I have the textfield call the str it gives me a numberformatexception, if I have it call the int variable it says it has to be a string...
public static String prePaidstr = "";
public static double prePaidint = 0;
prePaidstr =
JOptionPane.showInputDialog("Enter any amount prepaid:");
prePaidint = Double.parseDouble(prePaidstr);
jTextField13.setText(InvoiceSelectionUI.prePaidstr)
parseDouble converts a String into a Double, which is why it complains if you try to pass it a double.
A NumberFormatException is thrown when parseDouble is unable to successfully turn a String into a double; in this case it's because you're trying to parseDouble on an empty string. prePaidStr needs to contain something like "1.99" - e.g. something that, to a human, looks like a Double.
nm - I fixed it, just had one of the variables switched around

Categories