java用mvc写一个一元二次方程, 要有测试类,并给代码标准一下
时间: 2024-03-09 19:49:43 浏览: 241
好的,以下是一个使用MVC模式实现一元二次方程的Java代码:
Model层:Equation.java
```java
public class Equation {
private double a;
private double b;
private double c;
private double delta;
private double x1;
private double x2;
public void setCoefficient(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
calculateDelta();
calculateRoots();
}
private void calculateDelta() {
delta = b * b - 4 * a * c;
}
private void calculateRoots() {
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 getDelta() {
return delta;
}
public double getX1() {
return x1;
}
public double getX2() {
return x2;
}
}
```
View层:EquationView.java
```java
import java.util.Scanner;
public class EquationView {
private Scanner scanner;
public EquationView() {
scanner = new Scanner(System.in);
}
public void displayResult(double delta, double x1, double x2) {
if (Double.isNaN(x1) && Double.isNaN(x2)) {
System.out.println("该方程无实数解!");
} else if (delta == 0) {
System.out.println("该方程有唯一解:x=" + x1);
} else {
System.out.println("该方程有两个解:x1=" + x1 + ",x2=" + x2);
}
}
public double[] getCoefficient() {
double[] coefficient = new double[3];
System.out.println("请依次输入一元二次方程的系数:");
coefficient[0] = scanner.nextDouble();
coefficient[1] = scanner.nextDouble();
coefficient[2] = scanner.nextDouble();
return coefficient;
}
}
```
Controller层:EquationController.java
```java
public class EquationController {
private EquationView view;
private Equation model;
public EquationController(EquationView view, Equation model) {
this.view = view;
this.model = model;
}
public void processEquation() {
double[] coefficient = view.getCoefficient();
model.setCoefficient(coefficient[0], coefficient[1], coefficient[2]);
view.displayResult(model.getDelta(), model.getX1(), model.getX2());
}
}
```
测试类:EquationTest.java
```java
public class EquationTest {
public static void main(String[] args) {
EquationView view = new EquationView();
Equation model = new Equation();
EquationController controller = new EquationController(view, model);
controller.processEquation();
}
}
```
代码规范:
1. 类名采用大驼峰命名法,即每个单词首字母大写,比如EquationView、EquationController等;
2. 方法名采用小驼峰命名法,即第一个单词首字母小写,后面的单词首字母大写,比如setCoefficient、calculateDelta等;
3. 变量名采用小驼峰命名法,比如a、b、c、delta、x1、x2等;
4. 类、方法、变量等的命名要具有描述性,能够清晰表达其意义;
5. 代码中要有适当的注释,能够帮助他人理解代码的功能。
阅读全文