String value from a JTable to BigDecimal throws Java.lang.NumberFormatException - java

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.

Related

Why am I getting an error when checking if a string can be an double [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 4 years ago.
Hey guys im pretty new to coding but one of my projects is to check to see if a string can be parse into a double. It keeps printing an error when trying running the program.
Here is the code:
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
// Constant entered in by user as a string
out.println("Welcome to constant approximator");
out.println("Please enter in a constant to be estimated");
String realConstant = in.nextLine();
//Double variable created in order to reassign later
double test = 0;
//FormatChecker class and canParseDouble verifies if the string is truly a double. boolean method.
FormatChecker.canParseDouble(realConstant);
//Test reassign and converts
test = Double.parseDouble(realConstant);
out.print(test);
in.close();
out.close();
}
}
Here is the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "pi"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at ABCDGuesser1Test.main(ABCDGuesser1Test.java:36)
It happens because you type pi which is not recognized as π (pi) constant. What have you typed was a String and these characters are not convertible to a number.
If you want to enter any number including the special constant like pi, you have to check first if the input is a Number or String. In case it's String, you can try to match it with a defined constant like π or e and use their defined value in Java such as Math.PI.
You should use the result of canParseDouble() not just call it. Something like this, I think:
if (FormatChecker.canParseDouble(realConstant)) {
test = Double.parseDouble(realConstant);
out.println(test);
}
As you say:
//FormatChecker class and canParseDouble verifies if the string is truly a double. boolean method.
FormatChecker.canParseDouble(realConstant);
You know that this line calls a boolean method and will then return either true or false. However, you do not do any use of this returned value. If so, what's the point of even calling the function, right?
You are trying to check if the string realConstant is a double, the method checks it but you simply ignore it, here. I believe you have an error because whether it is truly a double or not, the rest of the code will run. In the case where the string is not actually a double, an error will appear since the rest of the code cannot compile.
You should then use an if statement such as:
if (FormatChecker.canParseDouble(realConstant)) {
test = Double.parseDouble(realConstant);
out.println(test);
}
Also, I do not think you should expect an input of "pi" to return a double!

Java: NumberFormatException in converting string to integer

I want to retrieve value from textbox and convert it to integer. I wrote the following code but it throws a NumberFormatException.
String nop = no_of_people.getText().toString();
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
The first call to System.out.println prints me the number but converting to integer gives an exception. What am I doing wrong?
Note that the parsing will fail if there are any white spaces in your string. You could either trim the string first by using the .trim method or else, do a replace all using the .replaceAll("\\s+", "").
If you want to avoid such issues, I would recommend you use a Formatted Text Field or a Spinner.
The latter options will guarantee that you have numeric values and should avoid you the need of using try catch blocks.
Your TextBox may contain number with a white space. Try following edited code. You need to trim the TextBox Value before converting it to Integer. Also make sure that value is not exceeding to integer range.
String nop=(no_of_people.getText().toString().trim());
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
Try this:
int nop1 = Integer.parseInt(no_of_people.getText().toString().trim());
System.out.println(nop1);
I would suggest replacing all non-digit characters from String first converting to int:
replaceAll("\\D+", "");
You can use this code:
String nop=(no_of_people.getText().toString().replaceAll("\\D+", ""));
System.out.printf("nop=[%s]%n", nop);
int nop1 = Integer.parseInt(nop);
System.out.printf("nop1=[%d]%n", nop1);

Convert String to 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]);
}

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

Is J2ME's Integer.parseInt() broken?

While writing a game for J2ME we ran into an issue using java.lang.Integer.parseInt()
We have several constant values defined as hex values, for example:
CHARACTER_RED = 0xFFAAA005;
During the game the value is serialized and is received through a network connection, coming in as a string representation of the hex value. In order to parse it back to an int we unsuccesfully tried the following:
// Response contains the value "ffAAA005" for "characterId"
string hexValue = response.get("characterId");
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
Then I ran some tests and tried this:
string hexValue = Integer.toHexString(0xFFAAA005);
// The following throws a NumberFormatException
int value = Integer.parseInt(hexValue, 16);
This is the exception from the actual code:
java.lang.NumberFormatException: ffaaa005
at java.lang.Integer.parseInt(Integer.java:462)
at net.triadgames.acertijo.GameMIDlet.startMIDlet(GameMIDlet.java:109)
This I must admit, baffled me. Looking at the parseInt code the NumberFormatException seems to be thrown when the number being parsed "crosses" the "negative/positive boundary" (perhaps someone can edit in the right jargon for this?).
Is this the expected behavior for the Integer.parseInt function? In the end I had to write my own hex string parsing function, and I was quite displeased with the provided implementation.
In other words, was my expectation of having Integer.parseInt() work on the hex string representation of an integer misguided?
EDIT: In my initial posting I wrote 0xFFFAAA005 instead of 0xFFAAA005. I've since corrected that mistake.
The String you are parsing is too large to fit in an int. In Java, an int is a signed, 32-bit data type. Your string requires at least 36 bits.
Your (positive) value is still too large to fit in a signed 32-bit int.
Do realize that your input (4289372165) overflows the maximum size of an int (2147483647)?
Try parsing the value as a long and trim the leading "0x" off the string before you parse it:
public class Program {
public static void main(String[] args) {
String input = "0xFFFAAA005";
long value = Long.parseLong(input.substring(2), 16);
System.out.print(value);
}
}
I'm not a java dev, but I'd guess parseInt only works with integers. 0xFFFAAA005 has 9 hex digits, so it's a long, not an int. My guess is it's complaining because you asked it to parse a number that's bigger than it's result data type.
Your number seems to be too large to fit in an int, try using Long.parseLong() instead.
Also, the string doesn't seem to get parsed if you have 0x in your string, so try to cut that off.

Categories