java编写一个应用程序,在窗口输入a、b、c三个数值,实现ax2+bx+c=0的求解,并将最终的求解的结果在窗口显示出来。
时间: 2024-03-15 10:43:53 浏览: 56
java 输入3个数a,b,c,按大小顺序输出的实例讲解
可以使用Swing实现一个简单的GUI程序,代码如下:
```java
import javax.swing.*;
public class QuadraticEquationSolver extends JFrame {
private JPanel panel;
private JLabel label1, label2, label3;
private JTextField text1, text2, text3;
private JButton button;
public QuadraticEquationSolver() {
super("Quadratic Equation Solver");
// 初始化组件
panel = new JPanel();
label1 = new JLabel("a:");
text1 = new JTextField(10);
label2 = new JLabel("b:");
text2 = new JTextField(10);
label3 = new JLabel("c:");
text3 = new JTextField(10);
button = new JButton("Solve");
button.addActionListener(e -> solveEquation());
// 将组件添加到面板中
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(label3);
panel.add(text3);
panel.add(button);
// 将面板添加到窗口中
setContentPane(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void solveEquation() {
double a = Double.parseDouble(text1.getText());
double b = Double.parseDouble(text2.getText());
double c = Double.parseDouble(text3.getText());
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
JOptionPane.showMessageDialog(this, "The equation has no real roots.");
} else if (discriminant == 0) {
double root = -b / (2 * a);
JOptionPane.showMessageDialog(this, "The equation has one root: " + root);
} else {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
JOptionPane.showMessageDialog(this, "The equation has two roots: " + root1 + " and " + root2);
}
}
public static void main(String[] args) {
new QuadraticEquationSolver();
}
}
```
这个程序使用了JTextField、JLabel和JButton等Swing组件,可以在窗口中输入a、b、c的值,并且点击“Solve”按钮进行求解。当方程有两个实根、一个实根或者无实根时,会在窗口中显示相应的结果。
阅读全文