我是Uni的一名學生,有編程任務。我們必須使用java製作計算器,其中一個要點是當用戶除以零時輸入消息「不是數字」。通常情況下,它會顯示「Infinity」,所以我們的任務就是改變這個信息,但是我並沒有去了解如何去做。如果任何人有想法或可以幫我改寫它,請在這裏留言。謝謝!Java計算器ActionListener。除以零時如何更改消息「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)'(或'if(!cond)')更容易,且不易出錯。 –
使用此方法檢查結果[Double#isInfinite()](https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#isInfinite-double-) – matoni
如何檢查臨時[1]'的價值在你做分裂之前?你很清楚'if'和'else'。 –