管理员能不能给俺们菜鸟点信心啊!我费了好半天劲,你就让我的帖子在主页多待会呗!
package cn.com.hrbust.Test;
//辗转相除
import java.util.Scanner;
public class JavaDemo {
static int r = 0;
static int x,y,num,m;
public static void main(String[]args) {
System.out.println("本程序的功能为求取最大公约数和最小公倍数,欢迎使用!");
System.out.println();
Scanner reader = new Scanner(System.in); //用Scanner接收键盘输入
System.out.println("请输入两个正整数: ");
x = reader.nextInt();
y = reader.nextInt();
System.out.println("*************************************");
System.out.println("求最大公约数,请按 1 回车! ");
System.out.println("求最小公倍数,请按 2 回车!");
System.out.println("最大公约数与最小公倍数均求取,请按 3 回车!");
System.out.println("************************************");
num = reader.nextInt();
switch (num) {//用switch判断调用哪个方法
case 1:
try { //求两个正整数的最大公约数和最小公倍数,所以菜鸟我自定义了一个异常类,如果键盘输入负数则会抛出异常
Gongyue();
} catch (MyException e) { //捕获异常 输出我在异常类中定义的输出内容
System.out.println(e.getMessage());
}
break;
case 2:
try {
Gongbei();
} catch (MyException e) {
System.out.println(e.getMessage());
}
break;
case 3:
try {
Gongyue();
} catch (MyException e) {
System.out.println(e.getMessage());
}
try {
Gongbei();
} catch (MyException e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
public static void Gongyue() throws MyException {
int z;
m = x*y; //键盘输入的两个数,有一个是负数则乘积也为负数
if(m<0) {
MyException e = new MyException();
throw(e);
}
if(x<y) {
z = x;
x = y;
y = z;
}
while(y%x>0) {
r = y%x;
y = x;
x = r;
}
System.out.println("最大公约数为:"+r);
}
public static void Gongbei() throws MyException{
int Ma;
int z;
m = x*y;
if(m<0) {
MyException e = new MyException();
throw(e);
}
if(x<y) {
z = x;
x = y;
y = z;
}
while(y%x>0) {
r = y%x;
y = x;
x = r;
}
Ma = x*y/r;
System.out.println("最小公倍数为: "+Ma);
}
}
/*
下面是我自己定义的异常类
*/
class MyException extends Exception {
String message;
public MyException() {
message = "要求输入的为两个正整数,请检查你所输入的数字!";
}
public String getMessage() {
return message;
}
}