2017-03-08 29 views
1

我想知道你將如何去輸出其中的兩個文本框拖住NumberFormatException異常。NumberFormatException的2個文本框的Java

try 
    { 
     num1Convert = Integer.parseInt(num1Str); 
     num2Convert = Integer.parseInt(num2Str); 

     sumValue = num1Convert + num2Convert; 
     sumLabel.setText(sumText + Integer.toString(sumValue)); 
    } 
    catch(NumberFormatException nfe) 
    { 
     errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer"); 
     num1.requestFocus(); 


    } 

我的程序會比較兩個數字,然後返回相加的數字的價值,但我需要這兩個文本域的都扔回去異常輸出,但我不知道如何做到這一點。我在代碼中寫過需要輸出它的地方。

+1

如何對兩個單獨的try catch塊?或者這太明顯瞭解決方案? –

+0

的可能的複製[什麼是NumberFormatException異常,我該如何解決?(http://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it) – xenteros

回答

1

像這樣的東西應該做的:

String currentString = ""; 
try 
    { 
     currentString = num1Str; 
     num1Convert = Integer.parseInt(num1Str); 
     currentString = num2Str; 
     num2Convert = Integer.parseInt(num2Str); 

     sumValue = num1Convert + num2Convert; 
     sumLabel.setText(sumText + Integer.toString(sumValue)); 
    } 
    catch(NumberFormatException nfe) 
    { 
     // errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer"); 
     errorLabel.setText(currentString + " must be an integer"); 
     num1.requestFocus(); 

    } 
+0

這只是輸出一下就把香港專業教育學院的文本框,而不是說「NUM1」或「NUM2」必須是@ininprsr – Luke

+0

的整數最初分配「NUM1」 到currentString ..然後 「NUM2」 的字符串值.. –

+0

感謝@JayanandRaghuwanshi – Luke

2

如何:

try{ 
     num1Convert = Integer.parseInt(num1Str); 
    } 
    catch(NumberFormatException nfe) { 
     System.out.println("Exception in num1"); 
    } 
    try{ 
     num2Convert = Integer.parseInt(num2Str); 
    } catch(NumberFormatException nfe) { 
     System.out.println("Exception in num2"); 
    } 

    //EDIT 

    sumValue = num1Convert + num2Convert; 
    sumLabel.setText(sumText + Integer.toString(sumValue)); 
+0

但後來我怎麼去的嘗試捕捉我貼內所示添加兩個值? – Luke

+0

編輯答案 –

+0

這種運作良好,但它設置的計算值僅僅是一個整數這樣,例如,如果NUM1是5和NUM2爲5t它將sumvalue設置爲5,而不是等到數的例外是數量在計算值之前修復 – Luke