Fernie Barragan
Fernie Barragan

Reputation: 13

Copy and modify array elements

I had to write a loop for an array which wanted to use the oldScores in the output but instead newScores[0] = 20 and newScores[3] = 10. I pass my first run when it test for {10, 20, 30, 40,}. Which expects an out put of: 20 30 40 10. When it passes the first test it tests it again with oldScores = {199}, which expects an output of just 199.

     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;

     /* solution goes here */

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

    return;
     }
    }

The code I used is here

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

By the way the rest of the code cannot be changed, only the solution can be changed.

Upvotes: 0

Views: 3485

Answers (2)

snvrthn
snvrthn

Reputation: 385

You seems trying to create array newScores by rotating the elements in the array oldScores. And you don't need to do newScores[3] = oldScores[0]; in each loop, just do it only once.

Following solution will work for array of given SCORES_SIZE

for(i = 0; i < SCORES_SIZE - 1; i++){
    newScores[i] = oldScores[i + 1];
}
newScores[SCORES_SIZE - 1] = oldScores[0]; // set first element of "oldScores" to last element of "newScores"

Upvotes: 1

M.S.
M.S.

Reputation: 1091

You seem to be on the right track, but you are over-complicating the logic of your solution. Here is a simpler option:

System.arraycopy(oldScores, 0, newScores, 0, oldScores.length); // create copy of oldScores and place it in newScores.
newScores[0] = 20;
newScores[3] = 10;

Alternatively, if you do not wish to use System.arraycopy(), you can copy an array by simply iterating over every element. For example,

for(int i = 0; i < oldScores.length; i++) {
    newScores[i] = oldScores[i];
}

Upvotes: 1

Related Questions