简体   繁体   English

Java图形用户界面

[英]Java graphical user interface

I want to add two strings in java by getting data from two input fields. 我想通过从两个输入字段获取数据来在Java中添加两个字符串。 Result is shown in the 3rd field. 结果显示在第三个字段中。 I am using this code, but netbeans shows an error: 我正在使用此代码,但是netbeans显示错误:

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

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. 引发以指示应用程序已尝试将字符串转换为数字类型之一,但是该字符串没有适当的格式。

You will get a NumberFormatException if the text you entered isn't a proper number.Surround the parseFloat() statements in try-catch block. 如果输入的文本不是正确的数字,则将获得NumberFormatException围绕try-catch块中的parseFloat()语句。 "Ahsan" isn't a number and hence cannot be parsed. “ Ahsan”不是数字,因此无法解析。

Make this little modification to your code: 对您的代码进行一些小的修改:

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

If you get NumberFormatException it can happen in one of these 2 lines: 如果收到NumberFormatException则可能在以下两行之一中发生:

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

More specifically it is thrown from Float.parseFloat() . 更具体地说,它是从Float.parseFloat()抛出的。 You pass unparsable value to this method. 您将无法分析的值传递给此方法。 Check what jTextField1.getText() or jTextField2.getText() return. 检查返回的jTextField1.getText()jTextField2.getText() I believe that these fields are empty or contain text that cannot be interpreted as legal float . 我认为这些字段为空或包含无法解释为合法float文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM