是否可以通过组合 if
来使其更加简洁带有 &&
的语句或者是其他东西?我已经尝试了很多,但似乎无法使其发挥作用。如果我能得到关于一两行代码的任何示例,我将非常感激。订单必须保持原样。
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button[0])
display.append("7");
if (ae.getSource() == button[1])
display.append("8");
if (ae.getSource() == button[2])
display.append("9");
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("1");
if (ae.getSource() == button[9])
display.append("2");
if (ae.getSource() == button[10])
display.append("3");
if (ae.getSource() == button[11]) {
temporary[0] = Double.parseDouble(display.getText());
function[2] = true;
display.setText("");
}
if (ae.getSource() == button[12])
display.append(".");
if (ae.getSource() == button[13]) {
temporary[0] = Double.parseDouble(display.getText());
function[3] = true;
display.setText("");
}
if (ae.getSource() == button[14])
clear();
if (ae.getSource() == button[15])
getSqrt();
if (ae.getSource() == button[16])
getPosNeg();
if (ae.getSource() == button[17])
getResult();
if (ae.getSource() == button[18])
display.append("0");
}
最佳答案
在函数之外的某个地方,可能作为final
成员,我会定义一个哈希表。
final Map<JButton, String> translation = new HashMap<>();
translation.put(button[0], "7");
translation.put(button[1], "8");
translation.put(button[2], "9");
translation.put(button[4], "4");
translation.put(button[5], "5");
translation.put(button[6], "6");
translation.put(button[8], "1");
translation.put(button[9], "2");
translation.put(button[10], "3");
translation.put(button[12], ".");
translation.put(button[18], "0");
final Map<JButton, Integer> functions = new HashMap<>();
functions.put(button[3], 0);
functions.put(button[7], 1);
functions.put(button[11], 2);
functions.put(button[13], 3);
final Map<JButton, Runnable> runnables = new HashMap<>();
runnables.put(button[14], () -> { clear(); });
runnables.put(button[15], () -> { getSqrt(); });
runnables.put(button[16], () -> { getPosNeg(); });
runnables.put(button[17], () -> { getResult(); });
然后我将按如下方式使用它:
public void actionPerformed(ActionEvent ae) {
if(translation.keySet().contains(ae.getSource())
{
display.append(translation.get(ae.getSource());
return;
}
if(functions.keySet().contains(ae.getSource())
{
temporary[0] = Double.parseDouble(display.getText());
function[functions.get(ae.getSource())] = true;
display.setText("");
return;
}
if(runnables.keySet().contains(ae.getSource())
{
runnables.get(ae.getSource()).run();
return;
}
}
关于java - if 语句更简洁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49983549/