public class Demo8_2 {
public static void main(String[] args) {
LinearEquation li=new LinearEquation(1, 1, 1, 1, 5, 6);
System.out.println(li.getX());
System.out.println(li.getY());
}
}
class LinearEquation{
private double a,b,c,d,e,f,delt;
public LinearEquation(double a,double b,double c,double d,double e,double f) {
//函数传进了a,b,c,d,e,f这6个值,把值赋给全局变量
this.a=a;
this.b=b;
this.c=c;
this.d=d;
this.e=e;
this.f=f;
}
public boolean isSolvable(){
return (delt=a*d-b*c)!=0;
}
public double getX(){
if(isSolvable()){
return (e*d-b*f)/delt;
}else{
//System.out.println("The equation has no solution");
/**/必须返回以个double型的数据,但此时无解,没有正常可以返回的值
//即如果出错了,需要抛异常**
throw new IllegalArgumentException("The equation has no solution");
}
}
public double getY(){
if(isSolvable()){
return (a*f-e*c)/delt;
}else{
//System.out.println("The equation has no solution");
throw new IllegalArgumentException("The equation has no solution");
//类似将throw当做return
}
}
public double getA(){
return a;
}
public double getB(){
return b;
}
public double getC(){
return c;
}
public double getD(){
return d;
}
public double getE(){
return e;
}
public double getF(){
return f;
}
}
结果:Exception in thread “main” java.lang.IllegalArgumentException: The equation has no solution
at LinearEquation.getX(Demo8_2.java:30)
at Demo8_2.main(Demo8_2.java:5)