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
Related
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);
I've got a bug or something. I have a method that saves an article, like this:
class SaveArticleListener implements ActionListener {
//....
String s = textArticlePrice.getText().replace(',','.').replaceAll("\\s","");
double price = Double.parseDouble(s);
//....
}
Where textArticlePrice is a JFormattedTextField which configured like:
NumberFormat priceFormat = NumberFormat.getNumberInstance();
priceFormat.setMaximumFractionDigits(2);
priceFormat.setMinimumFractionDigits(2);
textArticlePrice = new JFormattedTextField(priceFormat);
textArticlePrice.setColumns(10);
And in the parseDouble method I'm getting every time:
java.lang.NumberFormatException: For input string: "123 456 789.00"
So replace works with a dot, but not with whitespace... Why?
You'd be better off using your NumberFormat to parse the String. Keep a reference to priceFormat, and then use
double price = priceFormat.parse(textArticlePrice.getText()).doubleValue();
The formatter that's being used to display the number is the same one then used to turn it back into a double so you know it's going to be parsing it in a compatible way.
Best of all is
double price = ((Number) textArticlePrice.getValue()).doubleValue();
which should work without any need for conversion if you've set your JFormattedTextField up properly. (The getValue() call returns an Object, so you need to cast it. It might return a Double or a Long, depending on what's in the text field, so the safe way to get a double out of it is to treat it as a Number, which is the supertype of both, and invoke its .doubleValue() method.)
Writing something that converts it into something that can be parsed by Double.parseDouble() is really not the right way to go because it's too fragile if the formatting of your text field changes later on.
Regarding your question" why doesn't it work with white spaces". White spaces are chars just like a,l,#,?,¡, but it only recognises ,12345, numbers together as a number, you cant make an int variable 'int number = 1 234; Its the same with parsing. Rather try,
s = s.replace(',','.');
s = s.replace(" ","");
Price = Double.parseDouble(s);
Assuming that '123 456 789.00' is one number.
please comment if this helped.
I did this now, it worked fine
String strNumber = "1 2 3 4 5 6.789";
double DblNumber = Double.parseDouble(strNumber);
System.out.Println(DblNumber);// this displays the number if your IDE has an output window
I am making a graphing calculator that allows the calculation of data with errors (i.e. 5 +-0.02). I have created an object named Numbers3 which in its attributes has a BigDecimal variable. When I input the data trough the console, everything works fine. The problem comes when I am trying to retreive the data from a JTable; I convert the object to String, but when it faces BigDecimal(String) it throws an exception:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:470)
at java.math.BigDecimal.<init>(BigDecimal.java:739)
This is how I am getting the object from a JTable to a String. This is working because when I print the return from .getClass() the output is java.lang.String):
String number = (String)(table.getValueAt(i,j));
Have also tried several other options, such as:
String number=new String(String.valueOf(table.getValueAt(i,j));
I would really appreciate any help with this problem.
Try to normalize string to fit BigDecimal requirements:
private static BigDecimal parse(String str) {
String normalized = str.replaceAll("\\s", "").replace(',', '.');
return new BigDecimal(normalized);
}
Above code removes all whitespace characters from input string (which are not allowed in BigDecimal constructor).
What is more - it replaces comma to decimal point if needed.
What does this statement do?
double value = Double.valueOf(fstNmElmntLst.item(k).getTextContent());
Quite a lot going on there...
Gets the text content from some list as a string
converts the string to a Double (object wrapper for primitive double)
unboxes the Double to a primitive double
We could break it down
String tmp = fstNmElmntLst.item(k).getTextContent(); // fetch some string
Double wrapper = Double.valueOf(tmp); // convert (parse string to a number)
double value = wrapper; // unbox
A more efficient way to do this would be to use the parseDouble utility function. This avoids an unnecessary intermediate object being created:
double value = Double.parseDouble(fstNmElmntLst.item(k).getTextContent());
If you're new to java, have a look at some starter tutorials on the oracle.com site, for example Number Classes tutorial. If you're ever unsure of a behaviour of particular function just look at the javadocs. Just google something like "Double.valueOf javadoc 6" or setup your IDE properly.
Here's the javadoc for Double.valueOf(String). It will give you the full info on expected inputs, outputs, and other useful info like exceptions, in this case the NumberFormatException, which is thrown if your text can't be interrupted as a number.
It takes a text content of an item with index k from some kind of list fstNmElmntLst and parses that text as a double value.
This is casting from string to double because of array element, but there should be array value numeric else exception will raise.
Apparently getTextContent returns String. The typical way to convert String to double is to use the valueOf method in the class Double. As one can convert from Double to the primitive type double, the way to convert a String to double is to pass the string to valueOf in Double.
I am working on an assignment in which I have been given the task of creating an arraylist of books. In my utility, I have a 3 arg constructor (String title, String author, double price).
In my main, I am to read the contents of a comma seperated value file (which contains a list of book titles, authors, and price all on seperate lines). We are to tokenize the contents of the file (which I am able to do), and we are then to instantiate an ArrayList that holds book objects only. For each book in the text file, we are to read the record, tokenize the record, and create a new book object from the tokenized field, and then add the object to the beginning of the arrraylist.
So my question is:
When I tokenize the file (using the String method split, as the assignment dictates), I end up with a line by line break down of the file (as I should). I think I then want to feed these values into my constructor, but the constructor only accepts args String, String, double, and of course my tokenized file is String, String, String. Is there any way to 'convert' (for lack of a better term) the last string value into a double (I know that doubles are primitive and Strings are not), but I thought i would ask you guys before I go back to the drawing board and figure out the correct way of doing this.
Thanks for your time.
Call Double.parseDouble()
Here is the Javadoc
Double.parseDouble(d); will convert String "1.23" into double 1.23. There is also the related Integer.parseInteger(i) and Boolean.parseBoolean(b); functions.
What you want to do is parse a string into a double (giving you the words so that you know what it's called).
In Java, you use
Double.parseDouble(String)
You need to parse the string to a double, the code to do this would look like this:
Double num = Double.parseDouble(String);
Always make sure that the string is numberal before converting it else it will throw a error.
Webtest w= new Webtest();
ArrayList<String> dd= w.getarraylist();
Object []array1 = dd.toArray();
double value = Double.parseDouble(dd.get(8));
System.out.println(value);
double x[]=new double[dd.size()];
for (int i = 0; i <x.length; i++) {
x[i]=Double.parseDouble(dd.get(i));
System.out.println(x[i]);
}