首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将变量赋值给数组不能正常工作(Java)

问将变量赋值给数组不能正常工作(Java)
EN

Stack Overflow用户
提问于 2012-10-23 13:28:11
回答 3查看 91关注 0票数 2

由于某种原因,只有数组中的最后一个值被赋值为values...why,是这样吗?

代码语言:javascript
复制
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  
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-10-23 13:30:50

因为在每次迭代中,您都要重新声明数组。

代码语言:javascript
复制
for(int i = 0; i < framesToBowl; i++) {
        scores = new int[2][framesToBowl];   // Here!!!

在每次迭代中,您都会说scores接收到一个新的、完全归零的向量。这就是为什么你只能看到最后一次迭代的值。

您可以通过将分数的初始化放在循环之外来解决此问题。

代码语言:javascript
复制
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;
}
票数 7
EN

Stack Overflow用户

发布于 2012-10-23 13:32:03

从for循环中取出数组初始化。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-10-23 13:33:18

在循环开始时重置数组。

得分=新的int2;

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

只需在for循环外部声明它,就可以解决您的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13024092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档