Hob*_*ers 5 java code-organization organization
标题并不是我的全部问题。从理论上讲,我知道如何组织代码,但我想要一些具体的、有用的指针。请在抱怨之前继续阅读。
我是 java 和 OOP(面向对象编程)的初学者,我真的很想学习如何更好地组织我的代码!在一两个月的时间里,我制作了一个计算器程序,里面有一些我想到的小功能,还内置了一些小笑话。第二次查看后,我意识到它的格式非常糟糕,几乎难以理解。如果可以的话,我想请一些更有经验的程序员为我指明正确的方向,告诉我应该做什么来修复它(例如,我可以把什么东西变成物体,我可以在哪里划分,等等)。
请注意,这是我第一次在这样的论坛上发帖,所以如果我需要澄清一些事情来帮助我,我做错了什么,我要求太多,请告诉我,以便我可以解决它我可以获得帮助。请不要只是将其标记为无效并将其归档以遗忘(就像 stackoverflow 中经常发生的那样)。另外,在有人问之前,不,这不是家庭作业,它是我自己自学 java 的成果(可能是为什么它效果不太好)。
这是源代码:
// This is the original Calculator code without objects in a single class. not really efficient...
package randomClasses;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
@SuppressWarnings("serial")
public class CalcClass
extends JFrame
implements ActionListener {
JPanel[] row = new JPanel[6];
JButton[] button = new JButton[21];
String[] buttonString = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "/", "C", "v", "+/-", "=", "0", "Parabola", "x^y"};
int[] dimW = {300, 45, 100, 90, 180};
int[] dimH = {35, 40};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
Dimension parabolaDimension = new Dimension(dimW[4], dimH[0]);
//formatting variables
int var = 0;
double x = 0;
String stor = "";
boolean initial = true;
//variables for Parabola function
int countEquals_parab = 0;
double Angle = 0;
double Vi = 0;
double Vx = 0;
double Vy = 0;
double T_max = 0;
double Y_displ = 0;
double X_displ = 0;
double h = 0;
double k = 0;
double a_parab = 0;
boolean parabComplete = true;
boolean parabola = false;
DecimalFormat df = new DecimalFormat("#######.#####");
//variables for addressing illegal typing issues
boolean typeNum = true;
boolean typeDot = true;
JFrame frame; //for parabolaInstructions
//original calculator variables
boolean[] function = new boolean[5];
double[] temporary = {0, 0}; //store on screen values
double result = 0; //store result
public JTextArea display = new JTextArea(1, 20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
CalcClass() {
super("CalcClass");
setDesign();
setSize(380, 300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(6, 5);
setLayout(grid);
for(int i = 0; i < 5; i++) {
function[i] = false;
}
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER, 1, 1);
for(int i = 0; i < 6; i++) {
row[i] = new JPanel();
}
row[0].setLayout(f1);
for(int i = 1; i < 6; i++) {
row[i].setLayout(f2);
}
for(int i = 0; i < 21; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 14; i++) {
button[i].setPreferredSize(regularDimension);
}
for(int i = 14; i < 18; i++) {
button[i].setPreferredSize(rColumnDimension);
}
button[18].setPreferredSize(zeroButDimension);
button[19].setPreferredSize(parabolaDimension);
button[20].setPreferredSize(rColumnDimension);
row[0].add(display);
add(row[0]);
for(int i = 0; i < 4; i++) {
row[1].add(button[i]);
}
row[1].add(button[14]);
add(row[1]);
for(int i = 4; i < 8; i++) {
row[2].add(button[i]);
}
row[2].add(button[15]);
add(row[2]);
for(int i = 8; i < 12; i++) {
row[3].add(button[i]);
}
row[3].add(button[16]);
add(row[3]);
row[4].add(button[18]);
for(int i = 12; i < 14; i++) {
row[4].add(button[i]);
}
row[4].add(button[17]);
add(row[4]);
row[5].add(button[19]);
row[5].add(button[20]);
add(row[5]);
setVisible(true);
}
public void getSqrt() {
stor = "";
initial = true;
try {
double value = Double.parseDouble(display.getText());
if(value == -100) {
format("John's Girlfriend");
} else {
value = Math.sqrt(Double.parseDouble(display.getText())); //create a value for variable, and use Maths square root to find the value
format(Double.toString(value)); //Sets display to new value
}
} catch(NumberFormatException e) {
}
typeDot = false;
typeNum = false;
}
public void getPosNeg() {
stor = "";
initial = true;
try {
double value = Double.parseDouble(display.getText()); //again creating a variable for current value
if(value != 0) { //if value is not equal to zero
value = (-1) * value; //multiplied by -1 to change the sign
format(Double.toString(value)); //Sets display to new value
} else {
}
} catch(NumberFormatException e) {
}
}
public void getResult() {
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp00 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp00[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp11 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp11[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
functions();
clear();
format(Double.toString(result));//display has a result
for(int i = 0; i < 5; i++) {
function[i] = false; //set all functions to false
}
} catch(NumberFormatException e) {
}
typeNum = false;
}
public void functions() {
if(function[2] == true) { //multiplication
result = temporary[0] * temporary[1];
} else if(function[3] == true) { //division
result = temporary[0] / temporary[1];
} else if(function[0] == true) { //addition
result = temporary[0] + temporary[1];
} else if(function[1] == true) { //subtraction;
result = temporary[0] - temporary[1];
} else if(function[4] == true) {
result = Math.pow(temporary[0], temporary[1]);
} else {
result = temporary[1];
}
}
double a_quadratic = 0;
double b = 0;
double c = 0;
double x1 = 0;
double x2 = 0;
double discr = 0;
int countEquals_quadratic = 0;
public void quadraticFormula() {
if(countEquals_parab == 0) {
a_quadratic = Double.parseDouble(display.getText());
clear();
display.setText("b = ");
}
if(countEquals_parab == 1) {
b = Double.parseDouble(display.getText());
display.setText("c = ");
}
if(countEquals_parab == 2) {
c = Double.parseDouble(display.getText());
discr = (Math.pow(b, 2) - 4 * a_quadratic * c); //stores the value of the discriminant
if(discr >= 0) {
x1 = (-b + Math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);
x2 = (-b - Math.sqrt(b * b - 4 * a_quadratic * c)) / (2 * a_quadratic);
}
}
}
public void parabolaButton() {
double G = 9.81;
if(countEquals_parab == 0) {
Vi = Double.parseDouble(display.getText());
clear();
display.setText("Angle of release: ");
}
if(countEquals_parab == 1) {
Angle = Double.parseDouble(display.getText());
if((Angle > 90.0) || (Angle < 0.0)) {
display.setText("Sorry, not a valid angle");
countEquals_parab = 3;
} else {
Angle = (Math.PI / 180.0) * Angle; //converting degrees into radians
Vx = Vi * Math.cos(Angle); //Calculating x component
Vy = Vi * Math.sin(Angle); //Calculating y component
//Finding time
T_max = Vy / G; //time to max height
//Calculating vertex coordinates
Y_displ = (Vy * Vy / (2 * G));
X_displ = Vx * T_max;
//finding a
a_parab = (-Y_displ) / (X_displ * X_displ);
display.setText("The equation of the parabola is \ny = " + df.format(a_parab) + "(x - " + df
.format(h) + ")^2 + " + df.format(k));
}
}
if(countEquals_parab == 2) {
display.setText("Time to get to max height = " + df.format(T_max));
}
if(countEquals_parab == 3) {
clearFunction();
countEquals_parab = -1;
parabola = false;
parabComplete = true;
}
countEquals_parab++;
}
public void var() {
var++;
if(var > 8) {
var = 1;
}
if(var == 1) {
format("x");
}
}
public final void setDesign() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public void format(String get) {
//get stores the incoming values temporarily
//get is transferred to a new value for permanent storage
//print the permanent storage value
//new number is added, stored temporarily in get
//get is added to permanent storage
//print permanent storage value
double spaceFix = 0;
if(initial == true) {
stor = get;
initial = false;
} else if(initial == false) {
stor = stor + get;
}
spaceFix = stor.length() / 4;
int numberOfSpaces = 56 - stor.length() + (int) spaceFix;
String format = String.format("%" + numberOfSpaces + "s", stor);
display.setText(format);
}
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0]) {
numberButtons("7");
}
if(ae.getSource() == button[1]) {
numberButtons("8");
}
if(ae.getSource() == button[2]) {
numberButtons("9");
}
if(ae.getSource() == button[3]) {
operatorButtons(0); //add function[0]
}
if(ae.getSource() == button[4]) {
numberButtons("4");
}
if(ae.getSource() == button[5]) {
numberButtons("5");
}
if(ae.getSource() == button[6]) {
numberButtons("6");
}
if(ae.getSource() == button[7]) {
operatorButtons(1); //subtract function[1]
}
if(ae.getSource() == button[8]) {
numberButtons("1");
}
if(ae.getSource() == button[9]) {
numberButtons("2");
}
if(ae.getSource() == button[10]) {
numberButtons("3");
}
if(ae.getSource() == button[11]) {
operatorButtons(2); //multiplication function[2]
}
if(ae.getSource() == button[12]) {
if(typeDot == false) {
} else {
numberButtons(".");
typeDot = false;
}
}
if(ae.getSource() == button[13]) {
operatorButtons(3); //divide function[3]
}
if(ae.getSource() == button[14]) {
clearFunction();
parabola = false;
parabComplete = true;
}
if(ae.getSource() == button[15]) {
getSqrt();
}
if(ae.getSource() == button[16]) {
getPosNeg();
}
if((ae.getSource() == button[17]) && display.getText().equals("")) {
} else if((ae.getSource() == button[17]) && (parabola == false)) {
getResult();
} else if((ae.getSource() == button[17]) && (parabola == true)) {
parabolaButton();
}
if(ae.getSource() == button[18]) {
numberButtons("0");
}
if(ae.getSource() == button[19]) {
clearFunction();
parabolaInstructions();
parabola = true;
parabComplete = false;
display.setText("Initial velocity: ");
}
if(ae.getSource() == button[20]) {
operatorButtons(4);//powerFunction();
}
}
public void parabolaInstructions() {
//Create the dialog.
final JDialog dialog = new JDialog(frame, "How to use the Parabola function");
//Add contents to it. It must have a close button,
//since some L&Fs (notably Java/Metal) don't provide one
//in the window decorations for dialogs.
JLabel label = new JLabel("<html><p align=center>" + "Step 1: Type in the initial velocity and press the \"=\" button<br>" + "Step 2: Type in the angle of Release (make sure that it is between 0 and 90)<br>" + "Step 3: Press the \"=\" button to scroll through the results<br>" + "Step 4: Profit");
label.setHorizontalAlignment(JLabel.CENTER);
Font font = label.getFont();
label.setFont(label.getFont().deriveFont(font.PLAIN, 14.0f));
JButton closeButton = new JButton("Ok");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
JPanel closePanel = new JPanel();
closePanel.setLayout(new BoxLayout(closePanel, BoxLayout.LINE_AXIS));
closePanel.add(Box.createHorizontalGlue());
closePanel.add(closeButton);
closePanel.setBorder(BorderFactory.
createEmptyBorder(0, 0, 5, 5));
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(label, BorderLayout.CENTER);
contentPane.add(closePanel, BorderLayout.PAGE_END);
contentPane.setOpaque(true);
dialog.setContentPane(contentPane);
//Show it.
dialog.setSize(new Dimension(400, 200));
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
public void numberButtons(String i) {
if(typeNum == false) {
display.setText("");
format(i);
} else {
format(i);
}
typeNum = true;
}
public void operatorButtons(int funct) {
if(display.getText().equals("")) {
} else {
temporary[0] = Double.parseDouble(display.getText());
function[funct] = true;
clear();
}
}
public void clearFunction() {
clear();
try {
for(int i = 0; i < 5; i++) {
function[i] = false;
}
for(int i = 0; i < 2; i++) {
temporary[i] = 0;
}
} catch(NullPointerException e) {
}
//For parabola()
Vi = 0;
Vx = 0;
Vy = 0;
T_max = 0;
Y_displ = 0;
X_displ = 0;
h = 0;
k = 0;
a_parab = 0;
}
public void clear() {
display.setText("");
stor = "";
typeDot = true;
initial = true;
}
public static void main(String[] arguments) {
CalcClass c = new CalcClass();
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,现在你已经看到了我的混乱......我有点知道我应该做什么,是的,我做了一些研究,但我觉得通过示例或良好的推动来学习组织比通过阅读要容易得多这些文章告诉您什么是对象的超假设或松散相似的示例。注意:我尝试使用方法来组织,我的类看起来比它所做的要好得多(我还将整个东西作为一个在底部调用的对象,这几乎没有用)。
感谢所有为我的问题做出贡献的人,我彻底废弃了这个垃圾,并使它好了 1000 倍。我从一开始就知道它制作得很差,我想修复它,但我不知道从哪里开始。在阅读了给出的所有建议、观看了一些教程并温习了一些简单的 java 概念(修饰符、jswing 等)之后,我最终制作了一个 MVC 格式的新概念(耶,顺序和效率)。现在我所有的新变量实际上都是有意义的(感谢@maaartinus 帮助我认识到我的许多变量命名不当,并使我的整个程序变得不必要的复杂)。另外,我尝试在 SRP 上工作(不是 100% 确定我是否完全做到了,但随着计划的组织,改变事情会很容易),我计划稍后添加单元以获得良好的实践(谢谢@Robert Snyder)。这个新的 GUI 很丑陋,但以后总是可以更改,而且由于它现在采用 MVC 格式,因此工作会更容易。
\n\n这是我所做的(尚未完成,远非完美,但朝着正确方向迈出了一步):
\n\nCalcGui.java
\n\npackage com.Calculator;\n\nimport java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\n\npublic class CalcGui extends JFrame {\n\nprivate static final long serialVersionUID = 1L;\nprivate String[] operatorsList = { "+", "-", "*", "/", "^" };\n\n// Row 1\nprivate JTextField firstNumber = new JTextField(10);\nprivate JComboBox<String> operator = new JComboBox<>(operatorsList);\nprivate JTextField secondNumber = new JTextField(10);\nprivate JButton calculateButton = new JButton("Calculate");\nprivate JTextField calcSolution = new JTextField(20);\n\n// Row 2\nprivate JLabel sqrtSymbol = new JLabel("\xe2\x88\x9a");\nprivate JTextField sqrtNumber = new JTextField(10);\nprivate JButton sqrtCalcButton = new JButton("Calculate");\nprivate JTextField sqrtCalcSolution = new JTextField(20);\n\n// Row 3\nprivate JLabel quadraticLabel1 = new JLabel("A = ");\nprivate JTextField quadraticFirstNumber = new JTextField(5);\nprivate JLabel quadraticLabel2 = new JLabel("B = ");\nprivate JTextField quadraticSecondNumber = new JTextField(5);\nprivate JLabel quadraticLabel3 = new JLabel("C = ");\nprivate JTextField quadraticThirdNumber = new JTextField(5);\nprivate JButton quadraticCalcButton = new JButton("Calculate");\nprivate JLabel quadraticTextBefore = new JLabel("x =");\nprivate JTextField firstQuadraticCalcSolution = new JTextField(3);\nprivate JLabel quadraticTextMiddle = new JLabel("and x =");\nprivate JTextField secondQuadraticCalcSolution = new JTextField(3);\n\nCalcGui() {\n\n JPanel calcPanel = new JPanel(new BorderLayout());\n FlowLayout Default = new FlowLayout(FlowLayout.LEFT);\n JPanel row1 = new JPanel(Default);\n JPanel row2 = new JPanel(Default);\n JPanel row3 = new JPanel(Default);\n\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n this.setSize(650, 150);\n\n row1.add(firstNumber);\n row1.add(operator);\n row1.add(secondNumber);\n row1.add(calculateButton);\n row1.add(calcSolution);\n\n row2.add(sqrtSymbol);\n row2.add(sqrtNumber);\n row2.add(sqrtCalcButton);\n row2.add(sqrtCalcSolution);\n\n row3.add(quadraticLabel1);\n row3.add(quadraticFirstNumber);\n row3.add(quadraticLabel2);\n row3.add(quadraticSecondNumber);\n row3.add(quadraticLabel3);\n row3.add(quadraticThirdNumber);\n row3.add(quadraticCalcButton);\n row3.add(quadraticTextBefore);\n row3.add(firstQuadraticCalcSolution);\n row3.add(quadraticTextMiddle);\n row3.add(secondQuadraticCalcSolution);\n\n calcPanel.add(row1, BorderLayout.NORTH);\n calcPanel.add(row2, BorderLayout.CENTER);\n calcPanel.add(row3, BorderLayout.SOUTH);\n this.add(calcPanel);\n\n}\n\n// basic calculations methods\npublic double getFirstNumber() {\n\n return Double.parseDouble(firstNumber.getText());\n\n}\n\npublic String getOperator() {\n\n return (String) operator.getSelectedItem();\n\n}\n\npublic double getSecondNumber() {\n\n return Double.parseDouble(secondNumber.getText());\n\n}\n\npublic void setCalcSolution(double solution) {\n\n calcSolution.setText(Double.toString(solution));\n\n}\n\nvoid addCalculateListener(ActionListener listenForCalcButton) {\n\n calculateButton.addActionListener(listenForCalcButton);\n\n}\n\nvoid displayErrorMessage(String errorMessage) {\n\n JOptionPane.showMessageDialog(this, errorMessage);\n\n}\n\n// Square root function methods\npublic double getSqrtNumber() {\n\n return Double.parseDouble(sqrtNumber.getText());\n\n}\n\npublic void setSqrtCalcSolution(double solution) {\n\n sqrtCalcSolution.setText(Double.toString(solution));\n\n}\n\nvoid addSqrtCalcListener(ActionListener listenForSqrtCalcButton) {\n\n sqrtCalcButton.addActionListener(listenForSqrtCalcButton);\n\n}\n\n// Quadratic formula Methods\npublic double getQuadraticFirstNumber() {\n\n return Double.parseDouble(quadraticFirstNumber.getText());\n\n}\n\npublic double getQuadraticSecondNumber() {\n\n return Double.parseDouble(quadraticSecondNumber.getText());\n\n}\n\npublic double getQuadraticThirdNumber() {\n\n return Double.parseDouble(quadraticThirdNumber.getText());\n\n}\n\npublic void setFirstQuadraticCalcSolution(double solution) {\n\n firstQuadraticCalcSolution.setText(Double.toString(solution));\n\n}\n\npublic void setSecondQuadraticCalcSolution(double solution) {\n\n secondQuadraticCalcSolution.setText(Double.toString(solution));\n\n}\n\nvoid addQuadraticCalcListener(ActionListener listenForQuadraticCalcButton) {\n\n quadraticCalcButton.addActionListener(listenForQuadraticCalcButton);\n\n}\n}\nRun Code Online (Sandbox Code Playgroud)\n\n计算模型.java
\n\npackage com.Calculator;\n\npublic class CalcModel {\n\nprivate double calcValue;\n\npublic void calculate(double firstNumber, double secondNumber,\n String operator) {\n\n if (operator.equals("+")) {\n\n calcValue = firstNumber + secondNumber;\n\n }\n\n if (operator.equals("-")) {\n\n calcValue = firstNumber - secondNumber;\n\n }\n if (operator.equals("*")) {\n\n calcValue = firstNumber * secondNumber;\n\n }\n if (operator.equals("/")) {\n\n calcValue = firstNumber / secondNumber;\n\n }\n\n if (operator.equals("^")) {\n\n calcValue = Math.pow(firstNumber, secondNumber);\n\n }\n}\n\npublic double getCalcValue() {\n\n return calcValue;\n\n}\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\nSqrtCalcModel.java
\n\npackage com.Calculator;\n\npublic class SqrtCalcModel {\n\nprivate double sqrtCalcValue;\n\npublic void sqrt(double number) {\n\n sqrtCalcValue = Math.sqrt(number);\n\n}\n\npublic double getSqrtCalcValue() {\n\n return sqrtCalcValue;\n\n}\n}\nRun Code Online (Sandbox Code Playgroud)\n\nQuadraticCalcModel.java
\n\npackage com.Calculator;\n\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\n\npublic class QuadraticCalcModel {\n\nprivate double firstQuadraticCalcValue;\nprivate double secondQuadraticCalcValue;\n\npublic void quadraticFormula(double a, double b, double c) {\n\n double discriminant = (b * b) - (4 * a * c);\n\n if (discriminant >= 0) {\n\n firstQuadraticCalcValue = (Math.sqrt((b * b) - (4 * a * c)) + (-b))\n / (2 * a);\n\n secondQuadraticCalcValue = (Math.sqrt((b * b) - (4 * a * c)) - (-b))\n / (2 * a);\n\n }\n\n else {\n\n JFrame parent = new JFrame();\n JOptionPane.showMessageDialog(parent,\n "This function has no real roots.");\n\n }\n\n}\n\npublic double getFirstQuadraticValue() {\n\n return firstQuadraticCalcValue;\n\n}\n\npublic double getSecondQuadraticValue() {\n\n return secondQuadraticCalcValue;\n\n}\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n计算器控制器.java
\n\npackage com.Calculator;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\npublic class CalculatorController {\n\nprivate CalcGui theGui;\nprivate CalcModel theCalcModel;\nprivate SqrtCalcModel theSqrtCalcModel;\nprivate QuadraticCalcModel theQuadraticCalcModel;\n\npublic CalculatorController(CalcGui theGui, CalcModel theCalcModel,\n SqrtCalcModel theSqrtCalcModel,\n QuadraticCalcModel theQuadraticCalcModel) {\n this.theGui = theGui;\n this.theCalcModel = theCalcModel;\n this.theSqrtCalcModel = theSqrtCalcModel;\n this.theQuadraticCalcModel = theQuadraticCalcModel;\n\n this.theGui.addCalculateListener(new CalcListener());\n this.theGui.addSqrtCalcListener(new SqrtCalcListener());\n this.theGui.addQuadraticCalcListener(new QuadraticCalcListener());\n}\n\nclass CalcListener implements ActionListener {\n\n public void actionPerformed(ActionEvent e) {\n\n double firstNumber, secondNumber = 0;\n String operator;\n\n try {\n\n firstNumber = theGui.getFirstNumber();\n operator = theGui.getOperator();\n secondNumber = theGui.getSecondNumber();\n\n theCalcModel.calculate(firstNumber, secondNumber, operator);\n\n theGui.setCalcSolution(theCalcModel.getCalcValue());\n\n }\n\n catch (NumberFormatException ex) {\n\n System.out.println(ex);\n\n theGui.displayErrorMessage("You Need to Enter 2 Numbers");\n\n }\n }\n}\n\nclass SqrtCalcListener implements ActionListener {\n\n public void actionPerformed(ActionEvent e) {\n\n double number = 0;\n\n try {\n\n number = theGui.getSqrtNumber();\n\n theSqrtCalcModel.sqrt(number);\n\n theGui.setSqrtCalcSolution(theSqrtCalcModel.getSqrtCalcValue());\n\n }\n\n catch (NumberFormatException ex) {\n System.out.println(ex);\n\n theGui.displayErrorMessage("You Need to enter a Number");\n }\n }\n}\n\nclass QuadraticCalcListener implements ActionListener {\n\n public void actionPerformed(ActionEvent e) {\n\n double a, b, c = 0;\n\n try {\n\n a = theGui.getQuadraticFirstNumber();\n b = theGui.getQuadraticSecondNumber();\n c = theGui.getQuadraticThirdNumber();\n\n theQuadraticCalcModel.quadraticFormula(a, b, c);\n\n theGui.setFirstQuadraticCalcSolution(theQuadraticCalcModel\n .getFirstQuadraticValue());\n\n theGui.setSecondQuadraticCalcSolution(theQuadraticCalcModel\n .getSecondQuadraticValue());\n\n }\n\n catch (NumberFormatException ex) {\n\n System.out.println(ex);\n\n theGui.displayErrorMessage("You need to enter 3 numbers.");\n }\n\n }\n}\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\nMVC计算器.java
\n\npackage com.Calculator;\n\npublic class MVCCalculator {\n\npublic static void main(String[] args) {\n\n CalcGui theGui = new CalcGui();\n\n CalcModel theCalcModel = new CalcModel();\n\n SqrtCalcModel theSqrtCalcModel = new SqrtCalcModel();\n\n QuadraticCalcModel theQuadraticCalcModel = new QuadraticCalcModel();\n\n new CalculatorController(theGui, theCalcModel, theSqrtCalcModel,\n theQuadraticCalcModel);\n\n theGui.setVisible(true);\n\n}\n}\nRun Code Online (Sandbox Code Playgroud)\n