将字符串从 JLabel 转换为可读的 int

Converting string into a readable int from a JLabel

我需要对 JLabel 中的数字应用兴趣方法。我可以设法从 Jtextfield 做到这一点,但由于某种原因我无法让它在 JLabel 上工作。

这是按下J按钮时启动的代码:

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    interest(Integer.parseInt(balanceLabel.getText()));

balanceLabel 是我尝试使用的标签的名称。

这是我按下按钮时返回的错误:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "£1000.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

我已经研究过这个问题,它似乎非常普遍,但出于某种原因,我无法将其他答案应用于我的情况,因为我缺乏这样做的知识。

好吧,据我所知,您正在尝试转换不是整数的“£”,因此您得到了一个例外。您还有一个整数无法处理的十进制值,因此也因此抛出异常。

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.


如果您知道一切都将是“£xxxx.xx”,您可以做什么,您可以更改此行吗

  interest(Integer.parseInt(balanceLabel.getText()));

至此

interest(Double.parseDouble(balanceLabel.getText().substring(1));

然后 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.

问题是 £.,因为您正在尝试进行 int 转换。

改为使用浮点数:

Float.parseFloat(balanceLabel.getText().substring(1));

这样你就可以得到小数值,这对货币来说很有意义。