Java实训——编写一个窗体程序,用于计算一元二次方程。

实训要求:

Java实训——编写一个窗体程序,用于计算一元二次方程。_第1张图片

代码:

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;
	}
}

运行:

Java实训——编写一个窗体程序,用于计算一元二次方程。_第2张图片

小结:刚开始看的头晕眼花的,但只要搞清内部结构就容易理解了。

你可能感兴趣的:(Java)