0

Divisible challenge

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); String str = sc.nextLine(); String[] nums = str.split(" "); Boolean check = false; System.out.println(num); for(String s: nums){ int val = Integer.parseInt(s); if(num%val==0){ check = true; }else{ check = false; } } if(check){ System.out.println("divisible by all"); }else{ System.out.println("not divisible by all"); } } } I wrote this code and it is giving me an error but I couldn't find what's wrong

15th Oct 2024, 7:16 PM
Solomon Debesai
Solomon Debesai - avatar
3 Respuestas
+ 3
The issue in your code is in for loop it is overwriting the check value. That's the reason it is giving an error. Instead of a if statement you can use while loop if it is true then come out of the loop by stating the break statement.
15th Oct 2024, 7:54 PM
Aysha
Aysha - avatar
+ 2
Scanner class for sure is raising a issue here. Since the first input call only reads the integer and not a line break which is Yield by an enter key. After the program calls sc.nextLine() it reads thats leftover line break and assume the input as an empty string. Which is giving an error. To avoid the issue just add a sc.nextLine() after the first input call. Which will consume the extra line break. int num = sc.nextInt(); sc.nextLine(); String[] nums = str.split(" "); This should work fine.
16th Oct 2024, 1:57 AM
public static void
+ 1
public static void thank you, as you said the issue was in the Scanner class.
16th Oct 2024, 5:24 AM
Solomon Debesai
Solomon Debesai - avatar