0

I am having trouble printing the values of an array declared with ArrayList. I am using the enchanced for to print its values but what if i want to sum them.

import java.util.ArrayList;

import java.util.Scanner;

public class Program
{

public static void main(String[] args){

    int sum = 0;
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    Scanner input = new Scanner(System.in);
    int x = input.nextInt();

    while (x != -1){
        numbers.add(x);//xonoyme ta stoixeia ston numbers

        x = input.nextInt();
    }

    for (int y: numbers){
        sum = sum + numbers;
        System.out.print(y + " ");
    }
    System.out.print("to athroisma einai: " + sum);
}

}

the error is in the command sum = sum + numbers;

GhostCat
  • 137,827
  • 25
  • 176
  • 248

1 Answers1

1

Here:

sum = sum + numbers;

numbers is the list of numbers you are iterating on.

You probably meant:

sum = sum + y;

sum is a primitive int variable. The + operator only allows you to add other primitive numerical values here. You can't add a List<Integer> to an int value.

Alternatively, you can use Java 8 streams here:

numbers.stream().mapToInt(Integer::intValue).sum();

sums up all values in your list, too.

GhostCat
  • 137,827
  • 25
  • 176
  • 248