第九章第十一题(代数:2x2的线性方程)(Algebra: a linear equation of 2x2)
-
*9.11(代数:2x2的线性方程)为一个2x2的线性方程设计一个名为LinearEquation的类:
这个类包括:- 私有数据域a、b、c、d、e和f。
- 一个参数为a、b、c、d、e、f的构造方法。
- a、b、c、d、e、f的六个获取方法、
- 一个名为isSolvable()的方法,如果ad-bc不为0则返回true。
- 方法getX()和getY()返回这个方程的解。
画出该类的UML图并实现这个类。编写一个测试程序,提示用户输入a、b、c、d、e、f的值,然后显示结果。如果ad-bc为0,就报告“The equation has no solution”。参考编程习题3.3 的运行示例。
*9.11(Algebra: a linear equation of 2x2)Design a class called lineareequation for a 2x2 linear equation:
This class includes:- Private data fields a, B, C, D, e and F.
- A construction method of parameters a, B, C, D, e, F.
- Six acquisition methods of a, B, C, D, e, F
- A method called issolvable() returns true if ad BC is not 0.
- Methods geTx () and gety () return the solution of this equation.
Draw the UML diagram of the class and implement the class. Write a test program, prompt the user to input a, B, C, D, e, F values, and then display the results. If ad BC is 0, “the equation has no solution” is reported. Refer to the running example of programming exercise 3.3.
-
参考代码:
package chapter09;
public class Code_11 {
public static void main(String[] args){
LinearEquation expr1 = new LinearEquation(9.0,4.0,3.0,-5.0,-6.0,-21.0);
LinearEquation expr2 = new LinearEquation(1.0,2.0,2.0,4.0,4.0,5.0);
if(expr1.isSolvable()){
System.out.println("x:" + expr1.getX() + " " + "y:" + expr1.getY());
}
else
System.out.println("The equation has no solution");
if(expr2.isSolvable()){
System.out.println("x:" + expr2.getX() + " " + "y:" + expr2.getY());
}
else
System.out.println("The equation has no solution");
}
}
class LinearEquation {
private double a, b, c, d, e, f;
public LinearEquation(double v1, double v2, double v3, double v4, double v5, double v6) {
a = v1;
b = v2;
c = v3;
d = v4;
e = v5;
f = v6;
}
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;
}
public boolean isSolvable() {
if ((a * d - b * c) != 0)
return true;
else
return false;
}
public double getX() {
return (e * d - b * f) / (a * d - b * c);
}
public double getY() {
return (a * f - e * c) / (a * d - b * c);
}
}
- 结果显示:
x:-2.0 y:3.0
The equation has no solution
Process finished with exit code 0