0
Pls help with this code, the challenge is in the code
4 ответов
+ 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
+ 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);
}
}
+ 1
Denise Roßberg
Thanks
0
Quantum
Thanks but why won't mine work?
I don't think I did anything wrong