![](/img/trans.png)
[英]java.lang.NumberFormatException: For input string: " 1"
[英]java.lang.NumberFormatException: For input string: “” javafx
public void calculer(ActionEvent event) {
String i1 = txt1.getText();
int tx1 = Integer.parseInt(i1);
t1.setText(Integer.toString(tx1));
String i2 = txt2.getText();
int tx2 = Integer.parseInt(i2);
t2.setText(Integer.toString(tx2));
String i3 = txt3.getText();
int tx3 = Integer.parseInt(i3);
t3.setText(Integer.toString(tx3));
String i4 = txt4.getText();
int tx4 = Integer.parseInt(i4);
t4.setText(Integer.toString(tx4));
String i5 = txt5.getText();
int tx5 = Integer.parseInt(i5);
t5.setText(Integer.toString(tx5));
}
此代碼引發以下異常:
Caused by: java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at fx2/sample.Controller.calculer(Controller.java:98)
... 62 more
您可以檢查該字段是否為空,如果是,則將 0 分配給變量,例如(因為您提到要創建賬單)。
為此,使用 i2 更改您的代碼片段,如下例所示:
String i2 = txt2.getText();
int tx2 = Integer.parseInt(i2);
t2.setText(Integer.toString(tx2));
至
String i2 = txt2.getText();
int tx2 = 0;
if(i2.length() > 0) {
tx2 = Integer.parseInt(i2);
}
t2.setText(Integer.toString(tx2));
您可以使用您擁有的所有代碼片段(對於 i1 到 i5)來執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.