Search code examples
javalistsum

How can I sum the numbers that are next to each other in the list and add that sum to the same list between the numbers that I sum?


the list basically needs to go from (e.g.) 3 2 4 into a 3 5 2 6 4 , where 5 is a sum of 3 and 2 and 6 is a sum of 2 and 4. numbers in a list are typed manually and a list can have an infinite size.

i think i have the base(if you can call it that), but I'm not sure how exactly I can sum the specific numbers in a list. Here's what I got so far

import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    List<Integer> list = new LinkedList<Integer>();
    
    int number;
    while (true){
      number = sc.nextInt();
      if(number==0)break;

      if(list.size()==0)
        list.add(number);
      else{

        // here's where I think the sum of numbers should be
        
        }
        list.add(i,number);
      }
    }
    System.out.println("result:");
    
        for (int n : list) {
            System.out.print(n + " ");
    }

    sc.close();
  }
}

Solution

  • I don't know what's that i you are using (I don't see it declared anywhere), but you don't need it.

    Your loop can behave as follows:

    int number;
    while (true) {
      number = sc.nextInt();
      if(number==0)
          break;
      if(list.size() == 0) {
        list.add(number);
      } else{
        list.add(list.get(list.size()-1) + number);
        list.add(number);
      }
    }
    

    EDITED: I see that you want the sum of each pair of consecutive input numbers.

    • If the list is empty, you just add the first number to the list.
    • Otherwise, you add the sum of the last element added to the list and the new input number, and then you add the new input number.