2014-02-16 175 views
0

我想通过从两个输入字段获取数据在java中添加两个字符串。结果显示在第三个字段中。我使用这个代码,但NetBeans的显示错误:Java图形用户界面

float num1,num2,result; 
num1=Float.parseFloat(jTextField1.getText()); 
num2=Float.parseFloat(jTextField2.getText()); 
result=num1+num2; 
jTextField3.setText(String.valueOf(result)); 
+4

错误是什么? –

+0

此代码是用于添加按钮时,我按下按钮显示大量的线程,并在出来这条消息是显示异常在线程“AWT-EventQueue-0”java.lang.NumberFormatException:对于输入字符串:“Ahsan” \t at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241) – user3315364

+0

是发布错误并且不要使用Netbeans GUI构建器(IMO) – Smitty

回答

2

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

你会得到一个NumberFormatException,如果你输入的文本不正确的number.Surround在try-catchparseFloat()语句。 “Ahsan”不是一个数字,因此不能被解析。

让这个小小的修改你的代码:

try{ 
    num1=Float.parseFloat(jTextField1.getText()); 
    num2=Float.parseFloat(jTextField2.getText()); 
    result=num1+num2; 
    jTextField3.setText(String.valueOf(result)); 
}catch(NumberFormatException e){ 
    e.printStackTrace(); 
} 
+1

+1:'Ahsan'确实不是一个数字,虽然它不错:) – AlexR

+0

但是,在farci中,“Ashan”被翻译为五个,所以为什么它不起作用?!开玩笑。 +1 –

+0

@peeskillet因为赃物。 xD –

1

如果你NumberFormatException它可以在这两条线之一发生:

num1=Float.parseFloat(jTextField1.getText()); 
num2=Float.parseFloat(jTextField2.getText()); 

更具体地说,它是从Float.parseFloat()抛出。您将不可分割的值传递给此方法。检查jTextField1.getText()jTextField2.getText()返回。我相信这些字段是空的或包含无法解释为合法的文本float