【问题标题】:exception in thread, for input string线程中的异常,用于输入字符串
【发布时间】:2021-11-06 09:02:32
【问题描述】:

我想从JTextField 获取文本并将其转换为字符串,以便在用户单击按钮时将整数与另一个数字相乘。

这就是我现在拥有的:

firstTextField = new JTextField();
firstTextField.setBounds(40, 200, 100, 40);
firstTextField.setText("Enter amount");
stringTextField = firstTextField.getText();
integerTextField = Integer.parseInt(stringTextField);

if (e.getSource() == secondButton) {
    System.out.println(Integer.parseInt(firstTextField.getText()) +45);
}

我做错了什么?

错误信息:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Enter amount"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:660)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at com.company.MyClass.<init>(MyClass.java:49)
at com.company.Main.main(Main.java:7)

【问题讨论】:

标签: java swing jtextfield gettext numberformatexception


【解决方案1】:

@jakob :首先,我强烈建议您阅读 java 的基础知识。 现在请看下面给出的例子。

例子:

1.String str1 = "helloworld"; // a variable of type String can have only alphabets
2.String str2 = "Hello123";  // can also have alpha-numeric 
3.String str3 = "@hello$123";  // can also have special characters and alpha-numeric as well
4.String str4 = "1234";  // Can have only numbers
5.String str5 = "99"; // Can also have only numbers

以上所有示例都是 String 类型。

如果您想将字符串解析为 Integer 类型,您只能使用 Ex : 4 和 5 中给出的字符串。

给定的字符串在解析Integer、Double、Long或Float时只能包含数字,否则将抛出异常.

【讨论】:

    【解决方案2】:

    因为现在您的代码在 JTextField 中设置了一个文本(“输入金额”),然后检索它并尝试将其转换为整数,所以“输入金额”不是整数。

    尝试在您捕获的事件之后检索它:)

    【讨论】:

    • 我不明白...(我是一个完整的java初学者)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多