复制和修改数组元素

这是原始提示:

编写一个循环,将newScores设置为左移一次的oldScores,将元素0复制到结尾。 例如:如果oldScores = {10,20,30,40},则newScores = {20,30,40,10}。

注意:这些活动可能会测试具有不同测试值的代码。 此活动将执行两个测试,第一个使用4个元素的数组(newScores = {10,20,30,40}),第二个使用1个元素的数组(newScores = {199})。 请参见如何使用zyBooks。

另请注意:如果提交的代码尝试访问无效的数组元素,例如4元素数组的newScores [9],则测试可能会生成奇怪的结果。 或者测试可能会崩溃并报告“程序结束从未到达”,在这种情况下,系统不会打印导致报告消息的测试用例。

这是我的代码:

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

这是我的输出:

测试oldScores = {10,20,30,40}

你的输出:20 30 40 10

✖测试oldScores = {199}

预期产出:199

你的输出:0

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

将值从oldscores复制到newscores的for循环在SCORES_SIZE == 1的情况下永远不会运行,因为SCORES_SIZE - 1 == 0 ,并且0 < 0立即为false。

移动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]; 

假设您唯一的其他检查是长度为1的数组,只需使用它即可

 if(oldscores.length==1) {newscores[0]=oldscores[0]; System.out.println(newscores[0]); } 

甚至更简单,

 if(oldscores.length==1) { System.out.println(oldscores[0]); }