我试图在我的计算器程序上实现此actionPerformed方法。我在创建循环时遇到问题,循环显示按钮并在按下时执行计算。顺便说一句,如果我使用if语句执行此操作,我可以解决我的问题,但我想让我的代码更清晰。 这是我的代码:
(define (point x y)
(cons x y))
(define (point-x p)
(car p))
(define (point-y p)
(cdr p))
(define (point-difference p1 p2)
(point (- (point-x p1) (point-x p2))
(- (point-y p1) (point-y p2))))
(define (cartesian-distance p1 p2)
(let ((diff (point-difference p1 p2)))
(sqrt (+ (sqr (point-x diff))
(sqr (point-y diff))))))
(cartesian-distance (point 0 0) (point 3 4)) ;; => 5
答案 0 :(得分:1)
我可以通过很多方式来解决这个问题,使用Action
API可能是我最喜欢的,但可能超出了此处要求的范围。
我认为你不需要使用循环,我认为它们不会比其他方法更有优势。
例如,您可以使用String
内置的正则表达式支持,只需检查按钮的文本。
这至少可以让你确定文本是数字还是操作符或其他命令,例如......
private final String[] bText = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "=", "/", "(", ")", "C", "CE"};
private JButton[] buttons = new JButton[bText.length];
public TestPane() {
setLayout(new GridLayout(0, 3));
for (int index = 0; index < bText.length; index++) {
String text = bText[index];
JButton btn = new JButton(text);
buttons[index] = btn;
btn.addActionListener(this);
add(btn);
}
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
String text = btn.getText();
if (text.matches("^[0-9]")) {
System.out.println(text + " is a number");
} else if (text.matches("^[=/\\(\\)*=\\-\\+]")) {
System.out.println(text + " is an operator");
} else {
System.out.println(text + " is some other command");
}
}
}