2017-03-08 45 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