0
我想在我的計算器程序上實現這個actionPerformed方法。我無法創建一個循環,它會顯示按鈕並在按下時執行計算。順便說一下,如果我通過使用if語句執行此操作,但我想使代碼更清晰,我可以解決我的問題。 這裏是我的代碼:使用循環執行actionPerformed(點擊按鈕)
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)));
}
}
請格式化你的代碼,所以它更容易閱讀和更好地解釋你的問題。你有什麼麻煩,爲什麼'if'有幫助? – ChiefTwoPencils
你可以通過使用'JButton btn =(JButton)arg0.getSource();'從這個事件中訪問按鈕,你應該使用'getText'或'getActionCommand'來確定要執行的動作 – MadProgrammer
我想知道我如何通過使用for循環來最小化代碼的長度。如果我通過使用if語句來做,我必須使用20個if語句,並且我想知道是否有更簡單的方法。即;循環。格式化抱歉,我會做。 – user7062312