将变量分配给数组无法正常工作(Java)

时间:2012-10-23 05:28:11

标签: java arrays

由于某些原因,只为数组中的最终值赋值......为什么会这样?

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  

3 个答案:

答案 0 :(得分: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 :(得分: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);
    }

}

答案 2 :(得分:0)

您在循环开始时重置阵列。

scores = new int [2] [framesToBowl];

这会不断重置得分数组。所以当你去底部阅读它时,只会调用它的最后一个实例。

只需在for循环之外声明它,这应该可以解决您的问题。