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;

5
  • 2
    sum = sum + y; Commented Oct 14, 2018 at 7:46
  • Possible duplicate: stackoverflow.com/questions/16242733/… Commented Oct 14, 2018 at 7:49
  • I will try and stay with the rules next time i post. sorry for the question above which lucks of details. Commented Oct 14, 2018 at 8:12
  • I accepted your answer. Thanks a lot for the advise. Commented Oct 16, 2018 at 16:58
  • I appreciate the quick comeback! Commented Oct 16, 2018 at 17:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Without using streams ( i am at the beginning of learning java), how about summing my array like sum = sum + numbers[y] . Why it doesn't work?
sum = sum + y does the job. but what is y anyway. Isn't it like the index variable used in any array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.