我很困惑我应该在哪里以及如何使用" isSolvable"方法。由于显而易见的原因,我需要使用它来检查并确保分母不为0。换句话说,我该如何使用" isSolvable"我在变量上创建的方法" x"和" y"?
import java.util.Scanner;
public class LinearEquations {
Scanner input = new Scanner(System.in);
private double a, b, c, d, e, f = 0;
double x, y;
public double getA () {
System.out.println("Enter the value of a: ");
double a = input.nextDouble();
return a;
}
public double getB () {
System.out.println("Enter the value of b: ");
double b = input.nextDouble();
return b;
}
public double getC () {
System.out.println("Enter the value of c: ");
double c = input.nextDouble();
return c;
}
public double getD () {
System.out.println("Enter the value of d: ");
double d = input.nextDouble();
return d;
}
public double getE () {
System.out.println("Enter the value of e: ");
double e = input.nextDouble();
return e;
}
public double getF () {
System.out.println("Enter the value of f: ");
double f = input.nextDouble();
return f;
}
private boolean isSolvable() {
if ((a * d) - (b * c) == 0){
return false;
}
return true;
}
public double getX() {
double x = ((e * d) - (b * f) / (a * d) - (b * c));
return x;
}
public double getY() {
double y = ((a * f) - (e * c) / (a *d) - (b * c));
return y;
}
}
感谢任何和所有帮助。
答案 0 :(得分:1)
可能是这样的
public double getX() {
if (isSolvable()) {
double x = ((e * d) - (b * f) / (a * d) - (b * c));
return x;
}
else {
throw new IllegalArgumentExceprion();
}
}
getY()
相同。
修改强>
使用它的一个例子是在使用这些方法的代码中捕获异常
public static void main(String[] args) {
...
LinearEquations le = ...;
try {
double x = le.getX();
} catch (IllegalArgumentException e) {
System.out.println("Equation is not solveable!");
return;
}
...
}