从Java中的计算器获取结果
我必须从单独的 JTextfield 计算两个输入,在组合框中选择一个运算符并根据所选运算符计算结果。然而,我得到的答案是 0。如何计算结果而不得到0?
private void jButton1_actionPerformed(ActionEvent e) {
int x = Integer.parseInt(jTextField1.getText());
int y = Integer.parseInt(jTextField2.getText());
String Result = "0";
jLabel4.setText(Result);
int total = Integer.parseInt(Result);
if(Operator.equals("+")) {
total = x + y;
}
else if(Operator.equals("-")) {
total = x - y;
}
else if(Operator.equals("*")) {
total = x * y;
}
else if(Operator.equals("/")) {
total = x / y;
}
}
I have to calculate two inputs from separate JTextfields, pick an operator in a combobox and calculate the result based on the operator chosen. However, I get 0 as my answer. How can I calculate the result without getting 0?
private void jButton1_actionPerformed(ActionEvent e) {
int x = Integer.parseInt(jTextField1.getText());
int y = Integer.parseInt(jTextField2.getText());
String Result = "0";
jLabel4.setText(Result);
int total = Integer.parseInt(Result);
if(Operator.equals("+")) {
total = x + y;
}
else if(Operator.equals("-")) {
total = x - y;
}
else if(Operator.equals("*")) {
total = x * y;
}
else if(Operator.equals("/")) {
total = x / y;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那是因为你在计算结果后没有更新jLabel4。
在
if
之后,您应该添加另一个jLabel4.setText(Integer.toString(result));
That's because you do not update jLabel4 after calculating the result.
After the
if
s you should have add anotherjLabel4.setText(Integer.toString(result));
在此代码中,
jLabel4
是结果标签。您要做的是首先将“0”分配给字符串结果,然后将其(“0”)设置为文本,然后进行计算。
你应该做的是先计算然后设置结果。
From this code the
jLabel4
is the result label.What You are doing is first you assign to String Result with "0", and the you set this ("0") as text then you calculate.
What You should do is to calculate first and then set the result.
您应该将该方法分为两部分:一部分负责结果的计算,另一部分负责显示。除此之外,您可能应该使用 double,否则除法会给您带来意想不到的结果,即 0(例如,在 1/2 的情况下)。
You should separate the method into two parts: one responsible for the calculation of the result and the other for displaying. In addition to that you probably should use double, otherwise the division will give you unexpected results, i.e. 0 (e.g. in case of 1/2).