Java用Mvc写一个一元二次方程
时间: 2024-03-31 12:33:56 浏览: 50
好的,以下是一个简单的Java MVC模式实现的一元二次方程计算器:
Model(模型):
```
public class QuadraticEquation {
private double a;
private double b;
private double c;
private double x1;
private double x2;
public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public void solve() {
double delta = b * b - 4 * a * c;
if (delta < 0) {
x1 = Double.NaN;
x2 = Double.NaN;
} else {
x1 = (-b + Math.sqrt(delta)) / (2 * a);
x2 = (-b - Math.sqrt(delta)) / (2 * a);
}
}
public double getX1() {
return x1;
}
public double getX2() {
return x2;
}
}
```
View(视图):
```
public class QuadraticEquationView {
private Scanner scanner;
public QuadraticEquationView() {
scanner = new Scanner(System.in);
}
public double getA() {
System.out.print("Enter a: ");
return scanner.nextDouble();
}
public double getB() {
System.out.print("Enter b: ");
return scanner.nextDouble();
}
public double getC() {
System.out.print("Enter c: ");
return scanner.nextDouble();
}
public void displayResult(double x1, double x2) {
if (Double.isNaN(x1) || Double.isNaN(x2)) {
System.out.println("No real roots");
} else if (x1 == x2) {
System.out.println("The only root is " + x1);
} else {
System.out.println("The two roots are " + x1 + " and " + x2);
}
}
}
```
Controller(控制器):
```
public class QuadraticEquationController {
private QuadraticEquation model;
private QuadraticEquationView view;
public QuadraticEquationController(QuadraticEquation model, QuadraticEquationView view) {
this.model = model;
this.view = view;
}
public void run() {
double a = view.getA();
double b = view.getB();
double c = view.getC();
model = new QuadraticEquation(a, b, c);
model.solve();
double x1 = model.getX1();
double x2 = model.getX2();
view.displayResult(x1, x2);
}
}
```
Main(主程序):
```
public class Main {
public static void main(String[] args) {
QuadraticEquation model = new QuadraticEquation(0, 0, 0);
QuadraticEquationView view = new QuadraticEquationView();
QuadraticEquationController controller = new QuadraticEquationController(model, view);
controller.run();
}
}
```
在控制台里运行Main类,按照提示输入三个参数a、b和c,程序将会计算出一元二次方程的两个根并输出。
阅读全文