+ 1

Java Code Problem

This code is supposed to allow a user to first input the length of an array, followed by every element of the array. Then I am supposed to go through the array and sum all the multiples of four and output that number. Example input 3, 4, 1, 8 = array [4, 1, 8]. My output would be 12 as there are two elements that are multiples of 4 whose sum is 12. My code works for 3/5 tests. The hidden tests are failing and I’m not sure why. Thank you for the help! 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 t: array) { if (t % 4 == 0) { sum += t; } } System.out.println(sum); } }

18th Oct 2020, 7:52 PM
Richard Villarreal
Richard Villarreal - avatar
3 ответов
0
I think you may missing any conditions there... Read carefully again..
18th Oct 2020, 10:37 PM
Jayakrishna 🇮🇳
0
Could you provide of an example input you might think would cause an issue? I know I dont have an else statement for the if (t%4==0), but I tried adding else {sum=sum}; and that resulted in the same 3/5 tests pass
19th Oct 2020, 2:26 AM
Richard Villarreal
Richard Villarreal - avatar
0
Not about else. I mean if there are dublicates may you no need to add to sum.. Like these conditions.. Because your code works to find just for sum of divisible of 4 perfectly..
19th Oct 2020, 12:38 PM
Jayakrishna 🇮🇳