Pls help with this code, the challenge is in the code | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Pls help with this code, the challenge is in the code

https://code.sololearn.com/cCC3XpB9yHbK/?ref=app

15th Dec 2021, 11:52 AM
Omobolaji
4 Antworten
+ 2
Omobolaji if(array[i] % 4 == 0) { for(int a = 0; a < array.length; a++) { sum += array[a]; } System.out.println(a); } This part is buggy. a) Variable i is from your first loop. Initializing a variable inside a loop means you can only use it inside this loop. (Variable scope: https://www.baeldung.com/java-variable-scope) b) In general you can put a loop inside an if statement. Means run this loop only when a condition is true. But it is not what you want. You want to loop through an array and check a condition. So your if statement should be inside your second loop. c) You want to print a. Look at a) why it can't work. And I think you want to print your sum and not a
15th Dec 2021, 5:04 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
I made some changes in your code, and here is a much simpler solution: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int length = scanner.nextInt(); int sum = 0; for (int i = 0; i < length; i++) { int num = scanner.nextInt(); if (num % 4 == 0) { sum += num; } } System.out.print(sum); } }
15th Dec 2021, 12:14 PM
Jan
Jan - avatar
+ 1
16th Dec 2021, 12:13 PM
Omobolaji
0
Quantum Thanks but why won't mine work? I don't think I did anything wrong
15th Dec 2021, 3:26 PM
Omobolaji