我是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();
}
}
答案 0 :(得分:0)
如你所知,除以零是无穷大。在java中,如果对原始包装类除以零则没有错误。例如
public static void main(String[] args) {
Double a = 1.0;
Double b = 0.0;
Double c = a/b;
c.isInfinite();
System.out.println(c.toString());
}
打印:
Infinity
所以,只需将结果形式double改为Double,然后:
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];
if(c.isInfinite() || c.isNaN()) {
display.setText("Not a number");
} else {
display.setText(result.toString());
}
for (int i = 0; i < 4; i++)
function[i] = false;
} catch (NumberFormatException e) {
display.setText(e.getMessage());
}
}