为一个2*2的线性方程设计一个名为LinearEquation的类:
ax + by = e cx + dy = f
x = (ed - bf) / (ad - bc) y = (af - ec) / (ad - bc)
这个类包括:
- 私有数据域a、b、c、d、e、和f。
- 一个参数为a、b、c、d、e、和f的构造方法。
- a、b、c、d、e、和f的六个get方法。
- 一个名为isSolvable()的方法,如果ad - bc 不为0则返回true。
- 方法getX()和getY()返回这个方程的解。
画出该类的UML图并实现这个类。编写一个程序,提示用户输入 a、b、c、d、e、和f的值,然后显示它的结果。如果 ad - bc 为0,就报告"The equation has no solution."。
UML类图:
——————————————————————————
LinearEquation
——————————————————————————
-a: double
-b: double
-c: double
-d: double
-e: double
-f: double
———————————————————————————
+LinearEquation(a: double, b: double,
c: double, d: double, e: double,
f: double)
+isSolvable(): boolean
+getX(): double
+getY(): double
+getA(): double
+getB(): double
+getC(): double
+getD(): double
+getE(): double
+getF(): double
———————————————————————————
package pack2;
import java.util.Scanner;
public class LinearEquation {
private double a, b, c, d, e, f; //系数
/**带全部系数的构造方法*/
public LinearEquation(double a, double b, double c, double d, double e, double f) {
this.a = a; this.b = b;
this.c = c; this.d = d;
this.e = e; this.f = f;
}
/**线性方程是否可解?*/
public boolean isSolvable() {
//a * d - b * c 不为0时返回true
return !(Math.abs(a * d - b * c) < 0.0001);
}
/**返回解X*/
public double getX() {
return (e * d - b * f) / (a * d - b * c);
}
/**返回解Y*/
public double getY() {
return (a * f - e * c) / (a * d - b * c);
}
/**返回a*/
public double getA() {
return a;
}
/**返回b*/
public double getB() {
return b;
}
/**返回c*/
public double getC() {
return c;
}
/**返回d*/
public double getD() {
return d;
}
/**返回e*/
public double getE() {
return e;
}
/**返回f*/
public double getF() {
return f;
}
//————————————————————————————————————————————————————
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter a, b, c, d, e, f: ");
LinearEquation liEquation = new LinearEquation(input.nextDouble(),
input.nextDouble(), input.nextDouble(), input.nextDouble(),
input.nextDouble(), input.nextDouble());
if(!liEquation.isSolvable())
System.out.println("The equation has no solution.");
else
System.out.println("X: " + liEquation.getX() + "\nY: " +
liEquation.getY());
}
}
}