Modify array elements using other elements

RickyRiccardo00 :

im having trouble figuring out my output isn't doing the correct thing. I'm new to java so bare with me. This is the piece of code i wrote for

         final int SCORES_SIZE = 4;
      int[] bonusScores = new int[SCORES_SIZE];
      int i;

      for (i = 0; i < bonusScores.length; ++i) {
         bonusScores[i] = scnr.nextInt();
      }


for (i = 0; i < 3; ++i) {
   bonusScores[i] = bonusScores[i+1]; 
}
      for (i = 0; i < bonusScores.length; ++i) {
         System.out.print(bonusScores[i] + " ");
      }
      System.out.println();
   }
}

right now im getting an output of |20 30 40 40| instead of |30 50 70 40|. I'm getting the error in my second for loop but im not sure how to correct it.

Don Hosek :

Your loop

for (i = 0; i < 3; ++i) {
   bonusScores[i] = bonusScores[i+1]; 
}

is doing exactly what you're telling it to do: copy the second element over the first, the third over the second, etc. so [10,20,30,40] becomes [20,20,30,40].

I'm guessing that you meant to do += instead of = from your description of the expected output.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31856&siteId=1