编写一个应用程序,在窗口输入a、b、c三个数值,实现ax2+bx+c=0的求解,并将最终的求解的结果在窗口显示出来。用Java实现
时间: 2024-03-15 20:46:13 浏览: 95
好的,我可以为您提供一个使用Java Swing库编写的GUI程序来实现您的需求。
下面是程序代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class QuadraticEquationSolver extends JFrame implements ActionListener {
private JTextField aTextField, bTextField, cTextField, resultTextField;
public QuadraticEquationSolver() {
setTitle("Quadratic Equation Solver");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
JLabel aLabel = new JLabel("a:");
aTextField = new JTextField(10);
JPanel aPanel = new JPanel();
aPanel.add(aLabel);
aPanel.add(aTextField);
JLabel bLabel = new JLabel("b:");
bTextField = new JTextField(10);
JPanel bPanel = new JPanel();
bPanel.add(bLabel);
bPanel.add(bTextField);
JLabel cLabel = new JLabel("c:");
cTextField = new JTextField(10);
JPanel cPanel = new JPanel();
cPanel.add(cLabel);
cPanel.add(cTextField);
JButton solveButton = new JButton("Solve");
solveButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(solveButton);
JLabel resultLabel = new JLabel("Result:");
resultTextField = new JTextField(20);
resultTextField.setEditable(false);
JPanel resultPanel = new JPanel();
resultPanel.add(resultLabel);
resultPanel.add(resultTextField);
Container container = getContentPane();
container.setLayout(new GridLayout(5, 1));
container.add(aPanel);
container.add(bPanel);
container.add(cPanel);
container.add(buttonPanel);
container.add(resultPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
double a = Double.parseDouble(aTextField.getText());
double b = Double.parseDouble(bTextField.getText());
double c = Double.parseDouble(cTextField.getText());
double delta = b * b - 4 * a * c;
if (delta < 0) {
resultTextField.setText("No real root!");
} else if (delta == 0) {
double x = -b / (2 * a);
resultTextField.setText("x = " + x);
} else {
double x1 = (-b + Math.sqrt(delta)) / (2 * a);
double x2 = (-b - Math.sqrt(delta)) / (2 * a);
resultTextField.setText("x1 = " + x1 + ", x2 = " + x2);
}
} catch (NumberFormatException exception) {
resultTextField.setText("Invalid input!");
}
}
public static void main(String[] args) {
QuadraticEquationSolver frame = new QuadraticEquationSolver();
frame.setVisible(true);
}
}
```
您可以复制代码并在本地运行。当您输入三个数值并单击"Solve"按钮时,程序将计算二次方程的根并在界面上显示结果。
阅读全文