【发布时间】:2017-07-02 19:56:15
【问题描述】:
我是 Uni 的一名学生,有一项编程作业。我们必须使用 java 制作一个计算器,其中一个要点是当用户除以零时输入一条消息“不是数字”。通常,它显示“Infinity”,因此任务是更改该消息,但是我并没有深入了解如何去做。如果有人有想法或可以帮助我重写它,请在此处发表评论。谢谢!
public void getResult() {
double result = 0;
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(function[2] == true)
result = temporary[0] * temporary[1];
else if(function[3] == true)
result = temporary[0] / temporary[1];
else if(function[0] == true)
result = temporary[0] + temporary [1];
else if(function[1] == true)
result = temporary[0] - temporary[1];
display.setText(Double.toString(result));
for(int i=0; i<4; i++)
function[i] = false;
} catch(NumberFormatException e) {}
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0])
display.append("1");
if(ae.getSource() == button[1])
display.append("2");
if(ae.getSource() == button[2])
display.append("3");
if(ae.getSource() == button[3]) {
temporary[0] = Double.parseDouble(display.getText());
function[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5])
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]) {
temporary[0] = Double.parseDouble(display.getText());
function[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("7");
if(ae.getSource() == button[9])
display.append("8");
if(ae.getSource() == button[10])
display.append("9");
if(ae.getSource() == button[11]) {
temporary[0] = Double.parseDouble(display.getText());
function[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append("0");
if(ae.getSource() == button[13])
display.append(".");
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15]){
temporary[0] = Double.parseDouble(display.getText());
function[3] = true;
display.setText("");
}
if(ae.getSource() == button[16])
getResult();
}
public static void main(String[] arguments) {
Calculator c = new Calculator();
}
}
【问题讨论】:
-
永远不要使用
if (cond == true)(或false):if (cond)(或if (!cond))更容易,更不容易出错。 -
用这个方法检查结果Double#isInfinite()
-
在进行除法之前检查
temporary[1]的值怎么样?你显然很熟悉if和else。
标签: java swing actionlistener