Mvc结构实现计算平方根
时间: 2024-03-09 20:47:15 浏览: 19
好的,这里提供一个基于MVC结构实现计算平方根的Java代码示例:
1. 模型(Model)部分
在模型部分,我们可以定义一个名为SquareRootModel的类,其中包含一个名为calculateSquareRoot的方法,用于计算输入数字的平方根。
```java
public class SquareRootModel {
public double calculateSquareRoot(double num) {
return Math.sqrt(num);
}
}
```
2. 视图(View)部分
在视图部分,我们可以定义一个名为SquareRootView的类,其中包含一个输入框、一个按钮和一个标签,用于输入数字、触发计算和显示计算结果。
```java
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SquareRootView extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField inputField;
private JButton calculateButton;
private JLabel resultLabel;
public SquareRootView() {
super("计算平方根");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inputField = new JTextField(10);
calculateButton = new JButton("计算");
resultLabel = new JLabel();
JPanel panel = new JPanel();
panel.add(inputField);
panel.add(calculateButton);
panel.add(resultLabel);
getContentPane().add(panel);
pack();
setVisible(true);
}
public double getInput() {
return Double.parseDouble(inputField.getText());
}
public void setResult(double result) {
resultLabel.setText("计算结果:" + result);
}
public void addCalculateListener(ActionListener listener) {
calculateButton.addActionListener(listener);
}
}
```
3. 控制器(Controller)部分
在控制器部分,我们可以定义一个名为SquareRootController的类,其中包含一个SquareRootModel对象和一个SquareRootView对象。在构造函数中,我们可以将视图中的按钮注册为监听器,并在监听器中调用模型中的方法来计算平方根,并将结果显示在视图中。
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SquareRootController {
private SquareRootModel model;
private SquareRootView view;
public SquareRootController(SquareRootModel model, SquareRootView view) {
this.model = model;
this.view = view;
view.addCalculateListener(new CalculateListener());
}
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double num = view.getInput();
double result = model.calculateSquareRoot(num);
view.setResult(result);
}
}
}
```
4. 主程序部分
最后,我们可以在主程序部分中创建一个SquareRootModel对象、一个SquareRootView对象和一个SquareRootController对象,来启动整个应用程序。
```java
public class SquareRootMVC {
public static void main(String[] args) {
SquareRootModel model = new SquareRootModel();
SquareRootView view = new SquareRootView();
SquareRootController controller = new SquareRootController(model, view);
}
}
```
以上就是一个基于MVC结构实现计算平方根的Java代码示例。希望能对您有所帮助!