gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:30:26 24 4
gpt4 key购买 nike

出于某种原因,只有数组中的最终值被赋值...这是为什么?

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

最佳答案

因为在每次迭代时您都会重新声明数组。

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

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

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

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;
}

关于java - 将变量分配给数组无法正常工作(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13024092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com