gpt4 book ai didi

java - 我该如何解决这个数组和循环?正确的输出但是

转载 作者:行者123 更新时间:2023-11-30 07:48:08 25 4
gpt4 key购买 nike

我的目标是编写一个循环,将 newScores 设置为 oldScores,左移一次,并将元素 0 复制到末尾。

编辑:这是我的主要问题,我初始化了 newScores[3] = oldScores[0]; 但问题是 for 循环使 i = 4 当没有 oldScores[4] 或 newScores[4] 但由于我将 newScores[3] 初始化为 oldScores[0] 时,它会编译并运行,但问题是 [4] 根本不在数组中。我该如何摆脱这个问题?我离得很近,但又很远,这让我很烦恼。

示例:

If oldScores = {10, 20, 30, 40}, then newScores = {20, 30, 40, 10}

有趣的是,我有正确的输出,但我正在使用的学习网站告诉我,我有正确的输出,但它也显示此“运行时错误(通常是由于无效的数组/vector 访问,除以 0等)。测试中止。”。

public class StudentScores {
public static void main (String [] args) {
final int SCORES_SIZE = 4;
int[] oldScores = new int[SCORES_SIZE];
int[] newScores = new int[SCORES_SIZE];
int i = 0;

oldScores[0] = 10;
oldScores[1] = 20;
oldScores[2] = 30;
oldScores[3] = 40;
newScores[3] = oldScores[0];
for(i=0; i<SCORES_SIZE-1; i++){
newScores[i] = oldScores[i +1];
}

for (i = 0; i < SCORES_SIZE; ++i) {
System.out.print(newScores[i] + " ");
}
System.out.println();

return;
}
}

最佳答案

问题出在第二个循环中,其中有++i。 i++ 和++i 有两种不同的含义。这是一个向您描述含义的链接。 What is the difference between ++i and i++? 。如果你改变它,你不应该再收到错误。以下是代码中的更改。

public class StudentScores {
public static void main (String [] args) {
final int SCORES_SIZE = 4;
int[] oldScores = new int[SCORES_SIZE];
int[] newScores = new int[SCORES_SIZE];
int i = 0;

oldScores[0] = 10;
oldScores[1] = 20;
oldScores[2] = 30;
oldScores[3] = 40;
newScores[3] = oldScores[0];
for(i=0; i<SCORES_SIZE-1; i++){
newScores[i] = oldScores[i +1];
}

for (i = 0; i < SCORES_SIZE; i++) {
System.out.print(newScores[i] + " ");
}
System.out.println();

return;
}
}

关于java - 我该如何解决这个数组和循环?正确的输出但是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33663329/

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