2014-12-06 72 views
0

该程序用于查找GCD,LCM。当程序到达while循环时,我遇到了问题。下面给出了我的代码。While循环在GCD中不起作用,LCM

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)); 
    } 
} 

错误:异常线程 “main” java.lang.ArithmeticException:/零在basicProgrammin.GCDLCM.main(GCDLCM.java:24)

请帮帮我,为什么我的while循环不工作? 在此先感谢。

回答

0

您可以使用try catch。 这是程序的例外,程序的逻辑运行时错误是异常情况。使用try catch您可以处理异常。 不允许被零除,请检查no是否大于零。

如果您尝试划分不小于零,则会发生以下ERROR: Exception in thread "main" java.lang.ArithmeticException:/by zero异常,因此首先检查no大于0,并尝试分割no或使用try catch执行异常处理。

while((a % b) != 0) { 

      a = b; 
      try 
     { 
      if(a>0) 
     { 
       b = a % b; 
     } 
     } 
    catch(Exception e) 
    { 
    System.out. print (e); 
    } 
    } 
+0

“对不起!现在还不行” – Sourov 2014-12-07 11:46:04