2013-07-28 44 views
0

請考慮下面的代碼:陣列和if語句:Array對象才能通行進入if語句

public JButton math_button[] = new JButton[5]; 
    for (int h = 0; h <math_button.length; h++) { 
     if(event.getSource()==math_button[h]) { 
      String button_press = math_button[h].getText();  
      if(math_button[h].getText().equals("Equals")) { 
       secondn = Integer.parseInt(math_input.getText()); 
       System.out.println(firstn + " math operator " + secondn + " and "+ math_button[h].getText()); 
       System.out.println(calc.Math(button_press, firstn, secondn)); 
      } else { 
       firstn = Integer.parseInt(math_input.getText()); 
       //math_input.setText(""); 
       //placeholder = calc.Math(math_button[h].getText(), firstn, secondn); 
       //int secondn = Integer.parseInt(math_input.getText()); 
       //int result = calc.Math(math_button[h].getText(), firstn, secondn); 
       //math_input.setText(Integer.toString(firstn)); 
       //math_input.setText(Integer.toString(placeholder)); 
      } 
     } 
    } 

是什麼,儘管變量button_press被設置爲一個數組對象的名稱第二之外的原因IF(嵌套)循環,測試條件變量math_button[h].getText()始終傳遞給calc.Math方法?

button_press字符串的變量是否被嵌套的IF語句覆蓋?

+2

使用'String#equals'來比較字符串。 '=='比較對象引用 – Reimeus

+0

Luiggi,我看到你指出可能的重複,但我從來沒有發現或者甚至想過詢問關於字符串比較的問題。 – obious

+0

@obious - 這裏的一個愚蠢的原因是(比較流行)關於比較Java中的String的問題是實際的問題/錯誤,對這個問題的任何答案都只是相同的答案。 –

回答

1

使用String#equals()作爲

if(math_button[h].getText().equals("Equal")) { 

的Equals ==操作者只相互比較的參考文獻;而不是實際的文字內容。

編輯

原因equals()沒有工作是因爲按鈕名稱爲Equals(注意s

public String[] name = {"Add", "Mulitply", "Divide", "Subtract", "Equals"}; 

因此,您if條件實際上應該是

if(math_button[h].getText().equals("Equals")) { 
+2

雖然你的回答是正確的,但是在可能的dup問題中已經說明了問題和解決方案 –

+0

謝謝,但我已經嘗試了你的建議,但它沒有奏效。 – obious

+0

@obious檢查更新。 ''' –