java编写一个类math,该类有如下方法:public int f (int a, int b){……//要求该方法返回a和b的最大公约数},再编写一个该类的子类lcmath,要求子类重写方法f(),而且重写的方法将返回两个整数的最小公倍数。要求从键盘键入a和b,在重写的方法的方法体中首先调用被隐藏的方法返回a和b的最大公约数m,然后将(a*b)/m返回;在应用的程序的主类中分别使用父类和子类创建对象,并分别调用方法f()计算两个正整数的最大公约数和最小公倍数
时间: 2024-02-10 17:10:33 浏览: 108
下面是 Java 代码实现:
```
import java.util.Scanner;
public class Math {
public int f(int a, int b) {
int min = Math.min(a, b);
for (int i = min; i >= 1; i--) {
if (a % i == 0 && b % i == 0) {
return i;
}
}
return 1;
}
}
public class LCMath extends Math {
@Override
public int f(int a, int b) {
int gcd = super.f(a, b);
return a * b / gcd;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入两个正整数:");
int a = scanner.nextInt();
int b = scanner.nextInt();
scanner.close();
Math math = new Math();
int gcd = math.f(a, b);
System.out.println(a + " 和 " + b + " 的最大公约数是 " + gcd);
LCMath lcmath = new LCMath();
int lcm = lcmath.f(a, b);
System.out.println(a + " 和 " + b + " 的最小公倍数是 " + lcm);
}
}
```
这段代码的运行结果如下:
```
请输入两个正整数:18 24
18 和 24 的最大公约数是 6
18 和 24 的最小公倍数是 72
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)