0

Summing elements in arrays

This code is supposed to find numbers that are multiples of 4 and add them up, and print the total. I get two different errors messages depending on where I decide to have the System.out statement, please look at the code, I placed a comment that shows the different error messages, the error messages point to the variable sum. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int length = scanner.nextInt(); int[] array = new int[length]; for (int i = 0; i < length; i++) { array[i] = scanner.nextInt(); } //your code goes here int sum = 0; for (int x = 0; x < length; x++){ if (array[x] % 4 = 0 ){ sum += array[x]; } else { sum = sum; } } //System.out.println(sum);**unexpected type } System.out.println(sum); }

30th Oct 2021, 8:51 PM
Natanael
5 Antworten
+ 2
//your code goes here int sum = 0; for(int x = 0; x < length; x++){ if(array[x] % 4 == 0) sum += array[x]; } System.out.println(sum);
30th Oct 2021, 9:20 PM
Solo
Solo - avatar
+ 1
Thank you so much, I've never made this mistake before, it's usually a semicolon or curly bracket that I'm missing.
31st Oct 2021, 12:37 AM
Natanael
0
If I use the last System.out statement the error message is <identifier expected>
30th Oct 2021, 8:54 PM
Natanael
30th Oct 2021, 9:25 PM
Stefanoo
Stefanoo - avatar