我正在尝试在计算器程序上实现此actionPerformed方法。我在创建一个循环时遇到麻烦,该循环将显示按钮并在按下时执行计算。顺便说一下,如果我可以使用if语句来解决此问题,但我想使代码更整洁,则可以解决我的问题。
这是我的代码:
String expr1 = "";
private static final String[] bText = {"7", "8", "9", "+", "4", "5", "6", "- ", "1", "2", "3", "*", "0", ".", "=", "/", "(", ")", "C", "CE"};
Button[] buttons = new Button[ bText.length ];
public void actionPerformed( ActionEvent arg0 ) {
String input = textField.getText();
// Trying to get the first 12 items for testing
for( int index = 0; index <=12; index++)
{
if(arg0.getSource()==buttons[index])
{
if(input.contains("1,2,3,4,5,6,7,8,9,0"))
{
textField.setText(input + bText[index]);
expr1 = expr1 + index;
}
if(input.contains("+-*/")){
expr1 = expr1 + bText[index];
textField.setText("");
}
}
}
for( int i=13; i <=16; i++){
if(arg0.getSource()==buttons[i]){
expr1 = expr1 + bText[i];
textField.setText("");
}
}
/**
If I do this one by one using if statements I can fix my problem but I want to make my code cleaner.
*/
//For CE button
if (arg0.getSource() == buttons[18]) {
String s = textField.getText().toString();
s = s.substring(0, s.length() - 1);
textField.setText(s);
}
else if(arg0.getSource()==buttons[17]) {
textField.setText("");
expr1 = "";
}
// This will calculate expressins. This is a "=" button
else if (arg0.getSource() == buttons[19]) {
System.out.println(expr1);
textField.setText("" + Integer.toString(calculatorEvaluator.eval(expr1)));
}
}
最佳答案
我可以想到很多方法来解决此问题,使用Action
s 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");
}
}
}