2012-10-23 42 views
2

出於某種原因,只有數組中的最終值被賦值......爲什麼會這樣呢?將變量賦值給數組無法正常工作(Java)

public void openFrameScores() { 
    int x = 0; 
    int y = 0; 
    int total = 0; 

    for(int i = 0; i < framesToBowl; i++) { 
     scores = new int[2][framesToBowl]; 
     x = (int)(Math.random() * 9); 
     if(x == 0) y = (int)(Math.random() * 9); 
     else y = (int)(Math.random() * (9 - x)); 
     scores[0][i] = x; 
     scores[1][i] = y; 
    } 

    for(int i = 0; i < framesToBowl; i++) { 
     total = total + scores[0][i] + scores[1][i]; 
     System.out.println("Frame: " + i + ", ball 1 = " + scores[0][i] + 
     ", ball 2 = " + scores[1][i] + ", total score = " + total); 
    } 

} 



------------------------------------------------ 

Frame: 0, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 1, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 2, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 3, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 4, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 5, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 6, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 7, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 8, ball 1 = 0, ball 2 = 0, total score = 0 
Frame: 9, ball 1 = 6, ball 2 = 1, total score = 7 
+1

我也有同樣的問題 – Dylansq

回答

7

因爲在每次迭代中你都要重新聲明數組。

for(int i = 0; i < framesToBowl; i++) { 
     scores = new int[2][framesToBowl]; // Here!!! 

在每次迭代中,您都會說分數接收到一個新的完全歸零向量。這就是爲什麼你只能看到最後一次迭代的價值。

您可以通過在循環外部對分數進行初始化來解決此問題。

scores = new int[2][framesToBowl]; 
for(int i = 0; i < framesToBowl; i++) { 
    x = (int)(Math.random() * 9); 
    if(x == 0) y = (int)(Math.random() * 9); 
    else y = (int)(Math.random() * (9 - x)); 
    scores[0][i] = x; 
    scores[1][i] = y; 
} 
+1

修復它取''=新int [2] [framesToBowl];'循環 – jlordo

+0

herpa derp。謝謝。 – ahota

0

從for循環取出數組初始化。

public void openFrameScores() { 
    int x = 0; 
    int y = 0; 
    int total = 0; 
scores = new int[2][framesToBowl]; 
    for(int i = 0; i < framesToBowl; i++) { 

     x = (int)(Math.random() * 9); 
     if(x == 0) y = (int)(Math.random() * 9); 
     else y = (int)(Math.random() * (9 - x)); 
     scores[0][i] = x; 
     scores[1][i] = y; 
    } 

    for(int i = 0; i < framesToBowl; i++) { 
     total = total + scores[0][i] + scores[1][i]; 
     System.out.println("Frame: " + i + ", ball 1 = " + scores[0][i] + 
     ", ball 2 = " + scores[1][i] + ", total score = " + total); 
    } 

} 
0

您在循環開始時重置您的數組。

scores = new int [2] [framesToBowl];

這不斷重置分數數組。所以當你去閱讀它的底部時,只會調用它的最後一個實例。

只需在for循環之外聲明它即可解決您的問題。

+1

Aww太晚:( – TyrZaraki