2014-03-02 34 views
-4

如何在按下按鈕時將按鈕轉到數組中的最後一個位置而不會收到indexoutofbound錯誤?Android Java Array indexoutofbound

switch (v.getId()) { 
    case R.id.back: 
     mainButton.setText(alphabet[position--]); 
     mainButton.setBackgroundColor(Color.rgb(randomColor, randomColor2, randomColor3)); 
     if (alphabet.equals("A")) { 
      mainButton.setText(alphabet[25]); 
     } 

     break; 
    case R.id.forward: 
     mainButton.setText(alphabet[position++]); 
     mainButton.setBackgroundColor(Color.rgb(randomColor, randomColor2, randomColor3)); 

     if (alphabet.equals("Z")) { 
      mainButton.setText(alphabet[0]); 
     } 
     break; 
    } 
+0

什麼是大小字母數組?? – Kick

+0

AZ ...它是26 @Youngistan – user3371326

+0

值的位置?? – Kick

回答

0

這應該工作,如果得到你想要做的。 首先計算數組的位置以便在邊界內。然後訪問數組的位置。

switch (v.getId()) { 
case R.id.back: 
    position--; 
    if(position<0) { position=25; } 
    // mainButton.setText(alphabet[position]); 
    // mainButton.setBackgroundColor(Color.rgb(randomColor, randomColor2, randomColor3)); 

    break; 
case R.id.forward: 
    position++; 
    if(position>25) { position=0; } 
    // mainButton.setText(alphabet[position]); 
    // mainButton.setBackgroundColor(Color.rgb(randomColor, randomColor2, randomColor3)); 

    break; 
} 
// for better improvement this can be added once for both cases 
mainButton.setText(alphabet[position]); 
mainButton.setBackgroundColor(Color.rgb(randomColor, randomColor2, randomColor3)); 

此檢查alphabet.equals("A"))有你正在嘗試比較字符串值數組,這將始終返回你假沒有實際意義。

+0

謝謝,這對我來說非常完美。 – user3371326

0

要停止IndexOutOfBoundsException,並從數組中的最後一個索引值你可以使用這個

alphabet[alphabet.length-1]); 

使用arrayname.length-1,而不是特定的索引號總是返回的最後一個索引,即使你的陣列有改變大小。儘管我相信你的代碼有更多的錯誤,而不僅僅是索引越界。

0

較短的解決方案甚至有人拿到了綠色的勾:(

{//your method... 
    switch (v.getId()) { 
     case R.id.back: 
      position--; 
      position = modulo(position, alphabet.length); 
      mainButton.setText(alphabet[position]); 
      mainButton.setBackgroundColor(Color.rgb(randomColor, randomColor2, randomColor3)); 

      break; 
     case R.id.forward: 
      position++; 
      position = modulo(position, alphabet.length); 
      mainButton.setText(alphabet[position]); 
      mainButton.setBackgroundColor(Color.rgb(randomColor, randomColor2, randomColor3)); 

      break; 
    } 
} 

private int modulo(int x, int y) { 
    return (int) (x - (y * Math.floor((double) x/(double) y))); 
} 

因此,當你-1position將變爲alphabet.length-1 當你拿到你的alphabet.length+1地位將改爲0