java用mvc写一个一元二次方程
时间: 2023-12-30 19:03:07 浏览: 154
好的,以下是一个简单的使用MVC模式实现一元二次方程的Java代码:
Model(模型):
```java
public class QuadraticEquation {
private double a;
private double b;
private double c;
private double discriminant;
private double root1;
private double root2;
public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
this.discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
this.root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
this.root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
}
}
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public double getDiscriminant() {
return discriminant;
}
public double getRoot1() {
return root1;
}
public double getRoot2() {
return root2;
}
}
```
View(视图):
```java
import java.util.Scanner;
public class QuadraticEquationView {
private Scanner scanner;
public QuadraticEquationView() {
scanner = new Scanner(System.in);
}
public double[] getInput() {
System.out.println("请输入一元二次方程的系数(a、b、c):");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
return new double[]{a, b, c};
}
public void printResult(double[] roots, double discriminant) {
if (discriminant > 0) {
System.out.println("该一元二次方程有两个实数根:");
System.out.printf("x1 = %.2f, x2 = %.2f\n", roots[0], roots[1]);
} else if (discriminant == 0) {
System.out.println("该一元二次方程有一个实数根:");
System.out.printf("x1 = x2 = %.2f\n", roots[0]);
} else {
System.out.println("该一元二次方程没有实数根,但有两个虚数根:");
System.out.printf("x1 = %.2f + %.2fi, x2 = %.2f - %.2fi\n", roots[0], Math.sqrt(-discriminant), roots[1], Math.sqrt(-discriminant));
}
}
}
```
Controller(控制器):
```java
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[] input = view.getInput();
model = new QuadraticEquation(input[0], input[1], input[2]);
double[] roots = new double[]{model.getRoot1(), model.getRoot2()};
double discriminant = model.getDiscriminant();
view.printResult(roots, discriminant);
}
}
```
Main(主函数):
```java
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();
}
}
```
使用MVC模式,我们将应用程序分为三个部分:模型(Model)、视图(View)和控制器(Controller)。模型负责计算并存储数据,视图负责输入和输出数据,控制器负责协调模型和视图之间的交互。这种分离使得应用程序更容易维护和扩展。
阅读全文