實訓要求:
代碼:
EquationException類:
import java.awt.*;import java.awt.event.*;import javax.swing.*;class EquationException extends RuntimeException {public static final int NONE_EQUATION = 1;public static final int NO_REALROOT = 2;private int errorCode;public EquationException(String msg, int errorCode) {super(msg);this.errorCode = errorCode;}public int getErrorCode() {return errorCode;}}public class EquationFrame extends JFrame implements ActionListener {SquareEquation equation;JTextField textA, textB, textC;JTextArea showRoots;JButton controlButton;public EquationFrame() {equation = new SquareEquation();textA = new JTextField(8);textB = new JTextField(8);textC = new JTextField(8);controlButton = new JButton("確定");JPanel pNorth = new JPanel();pNorth.add(new JLabel("二次項係數:"));pNorth.add(textA);pNorth.add(new JLabel("一次項係數:"));pNorth.add(textB);pNorth.add(new JLabel("常數項係數:"));pNorth.add(textC);pNorth.add(controlButton);controlButton.addActionListener(this);getContentPane().add(pNorth, BorderLayout.NORTH);showRoots = new JTextArea();JScrollPane scrollPane = new JScrollPane(showRoots);getContentPane().add(scrollPane, BorderLayout.CENTER);setSize(630, 160);Dimension scnSize = Toolkit.getDefaultToolkit().getScreenSize();Dimension frmSize = this.getSize();this.setLocation((scnSize.width - frmSize.width) / 2, (scnSize.height - frmSize.height) / 2);validate();setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public void actionPerformed(ActionEvent e) {try {double a = Double.parseDouble(textA.getText());double b = Double.parseDouble(textB.getText());double c = Double.parseDouble(textC.getText());equation.setA(a);equation.setB(b);equation.setC(c);showRoots.append("根:" + equation.getRootOne());showRoots.append(" 根: " + equation.getRootTwo() + "\n");} catch (Exception ex) {showRoots.append(ex.getMessage() + "\n");}}public static void main(String arg[]) {new EquationFrame();}}SquareEquation類:
public class SquareEquation {double a, b, c;public void setA(double a) {this.a = a;}public void setB(double b) {this.b = b;}public void setC(double c) {this.c = c;}public double getRootOne() {double disk = calculateValidDisk();return (-b + Math.sqrt(disk)) / (2 * a);}public double getRootTwo() {double disk = calculateValidDisk();return (-b - Math.sqrt(disk)) / (2 * a);}private double calculateValidDisk() {if (a == 0) {throw new EquationException("不是二次方程", EquationException.NONE_EQUATION);}double disk = b * b - 4 * a * c;if (disk < 0) {throw new EquationException("沒有實根", EquationException.NO_REALROOT);}return disk;}}
運行:
小結:剛開始看的頭暈眼花的,但只要搞清內部結構就容易理解了。