📄 equationmainclass.java
字号:
import java.awt.*;
import java.awt.event.*;
class SquareEquation
{ double a,b,c;
double root1,root2;
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() throws NoRealRootException,NoSquareEquationException
{ if(a!=0)
{ double disk=b*b-4*a*c;
if(disk>=0)
{ root1=(-b+Math.sqrt(disk))/(2*a);
}
else
{ throw new NoRealRootException("没有实根");
}
}
else
{ throw new NoRealRootException("不是二次方程");
}
return root1;
}
public double getRootTwo() throws NoRealRootException,NoSquareEquationException
{ if(a!=0)
{ double disk=b*b-4*a*c;
if(disk>=0)
{ root2=(-b-Math.sqrt(disk))/(2*a);
}
else
{ throw new NoRealRootException("没有实根");
}
}
else
{ throw new NoRealRootException("不是二次方程");
}
return root2;
}
}
class NoRealRootException extends Exception
{ String message;
NoRealRootException(String s)
{ message=s;
}
public String getMessage()
{ return message;
}
}
class NoSquareEquationException extends Exception
{ String message;
NoSquareEquationException(String s)
{ message=s;
}
public String getMessage()
{ return message;
}
}
class EquationFrame extends Frame implements ActionListener
{ SquareEquation equation;
TextField textA,textB,textC;
TextArea showRoots;
Button controlButton;
public EquationFrame()
{ equation=new SquareEquation();
textA=new TextField(8);
textB=new TextField(8);
textC=new TextField(8);
showRoots=new TextArea();
controlButton=new Button("确定");
Panel pNorth=new Panel();
pNorth.add(new Label("二次项系数:"));
pNorth.add(textA);
pNorth.add(new Label("一次项系数:"));
pNorth.add(textB);
pNorth.add(new Label("常数项系数:"));
pNorth.add(textC);
pNorth.add(controlButton);
controlButton.addActionListener(this);//当前窗口作为controlButton的ActionEvent事件的监视器
add(pNorth,BorderLayout.NORTH);
add(showRoots,BorderLayout.CENTER);
setBounds(100,100,630,160);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{ try
{ double a=Double.parseDouble(textA.getText()); //textA调用方法获取其中的文本
double b=Double.parseDouble(textB.getText()); //textB调用方法获取其中的文本
double c=Double.parseDouble(textC.getText()); // textC调用方法获取其中的文本
double d=Math.sqrt(b*b-4*a*c);
equation.setA(a);
equation.setB(b);
equation.setC(c);
textA.setText(""+a);
textB.setText(""+b);
textC.setText(""+c);
showRoots.append("\n -b="+-b+" b*b-4*a*c的算术平方根为:"+d+" 2a="+2*a);
showRoots.append("\n 根:"+equation.getRootOne());
showRoots.append(" 根:"+equation.getRootTwo());
}
catch(Exception ex)
{ showRoots.append("\n"+ex+"\n");
}
}
}
public class EquationMainClass
{ public static void main(String args[])
{ EquationFrame frame=new EquationFrame();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -