java吧 关注:1,272,833贴子:12,781,396
  • 7回复贴,共1

求大佬帮忙看一下这个程序

只看楼主收藏回复

import java.util.Scanner;
class A{
int a,b,r;
public A(int a,int b){
this.a=a;
this.b=b;
}
public int calculate() {
r = a % b;
while (r != 0) {
a = b;
b = r;
r = a % b;
}
return b;
}
}
class B{
int a,b;
public B(int a,int b){
this.a=a;
this.b=b;
}
A Max=new A(a,b);
public int calculate2 (){
return (a*b)/Max.calculate();
}
}
public class test5 {
public static void main(String[] args){
int a,b;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
A test1=new A(a,b);
B test2=new B(a,b);
System.out.println("最大公约数为"+test1.calculate());
System.out.println("最小公因数为"+test2.calculate2());
}
}
为什么它会报java.lang.ArithmeticException异常?


IP属地:天津1楼2023-11-06 23:09回复
    除以除数,除数为0了,还有好好看报错日志,报错位置直接能找到


    IP属地:山东2楼2023-11-07 08:22
    收起回复
      2025-08-06 14:24:03
      广告
      不感兴趣
      开通SVIP免广告
      别卷了考公务员吧


      来自iPhone客户端4楼2023-11-08 10:12
      回复
        A Max = new A(a,b);
        这一行声明了B类的成员变量,java实例化的时候先为成员变量赋值执行这一行,这个时候a和b还没赋值,都是0,再执行构造函数赋值


        IP属地:浙江来自Android客户端5楼2023-11-08 11:21
        回复