Issue
Here is the original prompt:
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.
This is the code that I have:
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;
}
}
This is my output:
Testing for oldScores = {10, 20, 30, 40}
Your output: 20 30 40 10
✖ Testing for oldScores = {199}
Expected output: 199
Your output: 0
Why am I getting 0 for my second output test?
Solution
The for loop in which you copy the values from oldscores
to newscores
is never run in the case of SCORES_SIZE == 1
, since SCORES_SIZE - 1 == 0
, and 0 < 0
is false immediately.
Move the newScores[SCORES_SIZE - 1] = oldScores[0];
line outside the for loop:
for (i = 0; i < SCORES_SIZE - 1; i++) {
newScores[i] = oldScores[i + 1];
}
newScores[SCORES_SIZE - 1] = oldScores[0];
Answered By - Andy Turner
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)