Reputation: 73
I need to apply an interest method to a number in a JLabel. I can manage to do it from a Jtextfield, but for some reason I cannot get it to work on the JLabel.
Here is the code that is initiated when the Jbutton is pressed:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
interest(Integer.parseInt(balanceLabel.getText()));
balanceLabel is the name of the label I am trying to work with.
Here is the error that is returned when I press the button:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "£1000.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
I have researched the problem and it seems it is extremely common but for some reason I cannot apply other answers to my situation as I lack the knowledge to do so.
Upvotes: 1
Views: 2287
Reputation: 1044
Well, from what I can see you are trying to convert '£' which isn't an integer, so you are getting an exception for that. You also have a decimal value, which an integer cannot handle, so the exception is also being thrown for that reason.
public static int parseInt(String s) throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
Parameters: s - a String containing the int representation to be parsed
Returns: the integer value represented by the argument in decimal.
Throws: NumberFormatException - if the string does not contain a parsable integer.
what you could do, if you know that everything will be '£xxxx.xx," is you can change this line
interest(Integer.parseInt(balanceLabel.getText()));
to this
interest(Double.parseDouble(balanceLabel.getText().substring(1));
which would then return "1000.0"
public String substring(int beginIndex)
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
Parameters: beginIndex - the beginning index, inclusive.
Returns: the specified substring.
Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Upvotes: 1
Reputation: 4392
The problem is the £
AND the .
since you are trying an int conversion.
Use a float instead:
Float.parseFloat(balanceLabel.getText().substring(1));
This way you can have decimal values, which makes sense for currency.
Upvotes: 2