Click here to Skip to main content
15,074,483 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i'm trying to add the elements in an array with the one after them, except the last number and then output the numbers. for example:
If the users inputs: 10, 20, 30, 40
It should output: 30, 50, 70, 40
But after trying my code its adding up the first two number and last two numbers but not the middle two.
So its outputting: 30 20 70 40 where the 20 stays the same.
This is my code:

What I have tried:

import java.util.Scanner;
public class StudentScores {
   public static void main (String [] args) {
      Scanner scnr = new Scanner(System.in);
      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 < bonusScores.length; ++i) {
         bonusScores[i] = bonusScores[i] + bonusScores[++i];
      }
 
              
      for (i = 0; i < bonusScores.length; ++i) {
         System.out.print(bonusScores[i] + " ");
      }
      System.out.println();
   }
}
Posted
Updated 4-Aug-21 0:15am

1 solution

Try
Java
import java.util.Scanner;
public class StudentScores {
   public static void main (String [] args) {
      Scanner scnr = new Scanner(System.in);
      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 < bonusScores.length-1; ++i) {
         bonusScores[i] += bonusScores[i+1];
      }


      for (i = 0; i < bonusScores.length; ++i) {
         System.out.print(bonusScores[i] + " ");
      }
      System.out.println();
   }
}
   
Comments
Sai nathi 4-Aug-21 6:18am
   
thank you so much it worked
CPallini 4-Aug-21 6:21am
   
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900