gpt4 book ai didi

java - 复制和修改数组元素

转载 作者:行者123 更新时间:2023-12-01 21:46:03 28 4
gpt4 key购买 nike

这是原始提示:

Write a loop that sets newScores to oldScores shifted once left, with element 0 copied to the end. Ex: If oldScores = {10, 20, 30, 40}, then newScores = {20, 30, 40, 10}.

Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (newScores = {10, 20, 30, 40}), the second with a 1-element array (newScores = {199}). See How to Use zyBooks.

Also note: If the submitted code tries to access an invalid array element, such as newScores[9] for a 4-element array, the test may generate strange results. Or the test may crash and report "Program end never reached", in which case the system doesn't print the test case that caused the reported message.

这是我的代码:

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;

for (i = 0; i < SCORES_SIZE - 1; i++) {
newScores[3] = oldScores[0];
newScores[i] = oldScores[i + 1];
}

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

return;
}
}

这是我的输出:

测试旧分数 = {10, 20, 30, 40}

您的输出:20 30 40 10

✖ 测试 oldScores = {199}

预期输出:199

你的输出:0

为什么我的第二次输出测试得到 0?

最佳答案

在 for 循环中复制 oldscores 中的值至newscoresSCORES_SIZE == 1 的情况下永远不会运行,自 SCORES_SIZE - 1 == 0 ,和0 < 0立即为假。

移动newScores[SCORES_SIZE - 1] = oldScores[0]; for 循环外的行:

for (i = 0; i < SCORES_SIZE - 1; i++) {
newScores[i] = oldScores[i + 1];
}
newScores[SCORES_SIZE - 1] = oldScores[0];

关于java - 复制和修改数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001310/

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