Practical Training Requirements:
Code:
Equationexception class:
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 ("OK");
JPanel Pnorth = new JPanel ();
Pnorth.add (New JLabel ("two factor:"));
Pnorth.add (texta);
Pnorth.add (New JLabel ("First factor:");
Pnorth.add (TEXTB);
Pnorth.add (new JLabel ("constant factor:");
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 ("root:" + equation.getrootone ());
Showroots.append ("root:" + equation.getroottwo () + "\ n");
catch (Exception ex) {Showroots.append (Ex.getmessage () + "\ n"); }} Public static void Main (String arg[]) {new Equationframe (); }
}Squareequation class:
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 ("Not a two-time equation") equationexception.none_equation);
}
Double disk = b * b-4 * a * C;
if (disk < 0) {
throw new equationexception ("No real Roots", equationexception.no_realroot);
}
return disk;
}
Run:
Summary: Just start to look dizzy, but as long as the internal structure is easy to understand.