. Advertisement .
..3..
. Advertisement .
..4..
I’m trying to run a new project. I do a couple of things like this:
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;
}
}
But in my program, I am getting the warning:
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.
Can someone explain why the “ write a loop that sets newscores to oldscores shifted once left, with element 0 copied to the end.” issue happened? Where have I gone wrong? Thank you!
The cause: When
SCORES SIZE == 1
, thefor
loop that copies values fromoldscores
tonewscores
never runs sinceSCORES SIZE - 1 == 0
, and0 < 0
is false right away. This is what causes the issue to arise.Solution:
Shift the
newScores[SCORES_SIZE - 1] = oldScores[0];
the line which is outside thefor
loop:If you assume that the only other check is one array of length one, then simply use this
Or, you can do it even simpler.