+ 1

[SOLVED] Please, could you explain where my problem is? Thanks for help.

You want to take a list of numbers and find the sum of all of the even numbers in the list. Ignore any odd numbers. Task: Find the sum of all even integers in a list of numbers. Input Format: The first input denotes the length of the list (N). The next N lines contain the list elements as integers. Output Format: An integer that represents the sum of only the even numbers in the list. Sample Input: 9 1 2 3 4 5 6 7 8 9 Sample Output: 20 /// Here is, my code import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); int len = input.nextInt(); int[] arr; int sum = 0; for (int i = 0; i < len; i++){ arr = new int[i]; arr[i] = input.nextInt(); if (arr[i] % 2 == 0){ sum += arr[i]; } } System.out.println(sum); } }

19th Sep 2021, 3:31 PM
mesarthim
mesarthim - avatar
6 odpowiedzi
+ 3
It's creating new object again and again in loop with different different sizes for same reference (arr) https://code.sololearn.com/caklReb19hzh/?ref=app
19th Sep 2021, 3:57 PM
Nivya
Nivya - avatar
+ 2
Martin Taylor You're right. I'm just begginner in Java, so I have to do practice more, then I can see my errors easily. Thanks for your comment.
19th Sep 2021, 4:55 PM
mesarthim
mesarthim - avatar
+ 2
Nivya Thanks for help buddy!
19th Sep 2021, 4:55 PM
mesarthim
mesarthim - avatar
+ 1
I though, it must be work but it says "There is thread in main function."
19th Sep 2021, 3:34 PM
mesarthim
mesarthim - avatar