This program for finding out GCD,LCM. I am facing problem when the program reach to while loop.My code is given below.
public class GCDLCM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
int a,b;
if(x < y) {
a = y;
b = x;
while((a % b) != 0) {
a = b;
b = a % b;
}
System.out.println("GCD: "+b);
}
else {
a = x;
b = y;
while((a % b) != 0) {
a = b;
b = a % b;
}
System.out.println("GCD: "+b);
}
System.out.println("LCM: "+((x * y)/b));
}
}
ERROR: Exception in thread "main" java.lang.ArithmeticException: / by zero at basicProgrammin.GCDLCM.main(GCDLCM.java:24)
please help me, why my while loop is not working? Thanks in advance.
You can use
try catch
. This is exception of program.the exception is logical runtime error of program.using atry catch
you can handle the exception. The no is not allowed divided by zero please check no is greater than zero.If you try to divide no less than zero then following
ERROR: Exception in thread "main" java.lang.ArithmeticException: / by zero
exception occurs so first of all check no is greater than 0 and try to divide the no.or use a try catch to exception handling.