0

Java 22.1

Can anyone help me debug this code, please? https://www.sololearn.com/learning/1068 import java.util.Scanner; public static void main (String[] args) { Scanner sc = new Scanner (system.in) int size = sc.nextInt(); // State the length of the array. int[] nums = new int[size]; // Set the length of the array nums to the var size. int sum = 0; for (int i = 0; i < size; i++) { nums[i] = sc.nextInt(); if (i % 4 == 0) { sum += nums[i]; } }System.out.println(sum); sc.close(); } } I have put this code in Eclipse and debugged it. For some reason, it is missing 16 but including 7 in the first test so outputting 11 and missing 4 but including 32 in the second test so outputting 32. Does anyone have any ideas where I've gone wrong?

9th Sep 2021, 9:00 AM
Emma
4 Réponses
+ 3
Emma You have created an object of Scanner class which is 'sc' but you used Scanner and scanner to read inputs which is wrong. There should be sc.nextInt() inside and outside the loop. Also you did i % 4 which is wrong there should be num[i] % 4 Also there is System.in not system.in System is a class so name should start from Capital letter. Also you missed Semicolon after creating object of Scanner class. Here is right solution: import java.util.Scanner; class Program { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int size = sc.nextInt(); // State the length of the array. int[] nums = new int[size]; // Set the length of the array nums to the var size. int sum = 0; for (int i = 0; i < size; i++) { nums[i] = sc.nextInt(); if (nums[i] % 4 == 0) { sum += nums[i]; } } System.out.println(sum); sc.close(); } }
9th Sep 2021, 9:38 AM
A͢J
A͢J - avatar
+ 2
Thank you so much @AJ - SoloHelper. The Scanner issues were caused when copying the code across. It was the nums[] that fixed it. :)
9th Sep 2021, 9:47 AM
Emma
+ 1
Emma Check my previous answer again. I have also provided solution.
9th Sep 2021, 9:45 AM
A͢J
A͢J - avatar
+ 1
I think the problem is if(i%4==0) If i were to create an array of length 5, then the iterations will be 0, 1, 2, 3, 4 So, you enter 5 numbers, but this is what happens 0%4 ==0 -> TRUE 1%4 ==0 -> FALSE 2%4 ==0 -> FALSE 3%4 ==0 -> FALSE 4%4 ==0 -> TRUE Only the number associated with iteration 0 & iteration 4 will be added to your sum variable
9th Sep 2021, 10:10 AM
Rik Wittkopp
Rik Wittkopp - avatar