综合练习8 计算最大公约数
建Computer类,该类中有一个计算两个数的最大公约数的方法,如果向该方法传递负整数,该方法就会抛出自定义异常。
方法1:辗转相除法(欧几里得算法);
/*综合练习8 计算最大公约数
* 创建Computer类,该类中有一个计算两个数的最大公约数
* 的方法,如果向该方法传递负整数,该方法就会抛出自定义异常。
* 方法1:辗转相除法(欧几里得算法);
*
* */
package yccl;
import java.util.Scanner;
public class Zhlx8 {
public static int Gys(int a,int b)throws Exception {
if(a<0||b<0) {
throw new Exception("参数不能是负整数");
}
if(b == 0) {
return a;
}
return Gys(b,a%b);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数a:");
int a = sc.nextInt();
System.out.println("请输入第二个数b:");
int b = sc.nextInt();
try {
System.out.print("最大公约数为:");
System.out.println(Gys(a,b));
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
}