在表单中添加文本框(JAVA、Netbeans 7)
我是 JAVA 领域的新手,我正在开始尝试。我在 Netbeans 中制作了一个带有 3 个文本框的表单。然后,我尝试添加前两个文本框,并在单击按钮后将总和放入第三个文本框。我有以下代码,但它列出了输出(不是总和)。
示例:2+2 = 22, 3+34 = 334
我的代码如下:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String x = jTextField1.getText();
String y = jTextField2.getText();
jTextField3.setText(x + y);
}
I am new to the realm of JAVA and I am starting to play around. I have made a form in Netbeans with 3 Text Boxes. I am then trying to add those the first two text boxes and place the sum in the third once a button is clicked. I have the following code but it is listing the output together(not as a sum).
Example: 2+2 = 22, 3+34 = 334
My Code is below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String x = jTextField1.getText();
String y = jTextField2.getText();
jTextField3.setText(x + y);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为当您对 String 使用
+
运算符时,它不会将其相加,而是将 2 个字符串连接起来,因为字符串不一定总是包含数字。因此,您必须首先将字符串转换为 int (或任何其他数字类型),然后进行求和。试试这个:
注意
try..catch()
。这是因为有些可以写一个不能像“a324ad”
一样转换为int的字符串。It is because when you use
+
operator for String it will not add it but concat 2 strings because it is not necessary that string always holds a number. So you have to first convert your string to int (or any other numeric type) and then do the sum.Try this:
Notice the
try..catch()
. It is because some can write a string which can not be cast to int like"a324ad"
.字符串数据类型的
+
运算符连接字符串。如果您尝试将文本框中输入的两个数字相加,则需要将其转换为数字数据类型。对于整数,您可以使用Integer.parseInt()
。尝试
The
+
operator for string data type concatenates the strings. If you are trying to add the two numbers entered in the text boxes, you need to convert then to a numeric data type. For Integer, you can useInteger.parseInt()
.Try