2017-05-24 9 views
-6

代碼編寫在NetBeans 8.2我已經寫正確的代碼,我認爲,但文本區域得不到輸出

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {          
    int a=Integer.parseInt(jTextField1.getText()); 
    int b=Integer.parseInt(jTextField2.getText()); 
    int c=a+b; 
    jTextArea1.setText("addition is"+c); 
} 

和錯誤來了有點像this--請告訴WATS的mistake-

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "   3" 
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:569) 
    at java.lang.Integer.parseInt(Integer.java:615) 
    at addsf.jButton1ActionPerformed(addsf.java:95) 
    at addsf.access$000(addsf.java:11) 

和許多更多的是寫。 請指導。

+3

你的'String'有一個空格,可以考慮調用'trim()'。 – Berger

+0

您在「3」中擁有領先的空間 –

+0

您是否做過任何可能理解該問題的內容? – f1sh

回答

2

你正試圖解析一個整數,它應該只有數字,沒有別的。試試這個:

jTextField1.getText().trim()) 

這將基本上刪除您的字符串之前和之後的所有空白。 " 2 "變成"2"

但是,如果它不是一系列數字,那麼這也很容易出錯,在這種情況下,您應該使用try/catch塊。

+0

感謝兄弟... –

+0

你可以接受答案。 – ergonaut

+0

我來自印度和15年..我是這個領域的新感謝幫助,但你能告訴我,爲什麼我們必須使用trim()??? –

0

異常消息對你說,這有什麼不對您的輸入:

java.lang.NumberFormatException:對於輸入字符串:「3」

如果你看一下字符串,你可以發現3前面的空白,這是異常的原因。

int a = Integer.parseInt(" 3"); // leading white-space causes error 
int b = Integer.parseInt("3"); // OK 

要從輸入去除可能的空格,您可以使用方法String#trim();其中沒有開頭或結尾的空格返回新String

int c = Integer.parseInt(" 3".trim()); 

或者你可以使用String.replaceAll(regex, replacement);其替換匹配給由指定的替換reular表達字符串的所有序列。

int d = Integer.parseInt(" 3".replaceAll("\\s", "")); // \\s = white-space 

考慮使用JFormattedTextField而不是JTextFieldJTextField接受您寫入的任何內容(帶有字母/空格的數字),而在JFormattedTextField上,您可以應用僅接受數字的掩碼,因此用戶將無法插入字母。這是一個example

相關問題