Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Tags:

java

list

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();
  }
}
like image 254
blueplanet Avatar asked Nov 03 '25 06:11

blueplanet


1 Answers

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.
like image 100
Eran Avatar answered Nov 04 '25 22:11

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!