用Java窗口组件 编写-个应用程序,在窗口输入a、b、c三个数值,实现ax²+bx+c=0的求解,并将最终的求解的结果在窗口显示出来
时间: 2024-03-16 07:42:01 浏览: 59
用Java编写程序,求一元二次方程ax²+bx+c=0的根(系数在程序中给定),并输出。
好的,我可以为您提供一个简单的Java窗口程序,用于解决ax²+bx+c=0的方程。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class QuadraticEquationSolver extends JFrame implements ActionListener {
private JLabel label1, label2, label3, result;
private JTextField aField, bField, cField;
private JButton calculateButton;
public QuadraticEquationSolver() {
super("Quadratic Equation Solver");
label1 = new JLabel("Enter the value of a: ");
label2 = new JLabel("Enter the value of b: ");
label3 = new JLabel("Enter the value of c: ");
aField = new JTextField(10);
bField = new JTextField(10);
cField = new JTextField(10);
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
result = new JLabel(" ");
JPanel inputPanel = new JPanel(new GridLayout(3, 2));
inputPanel.add(label1);
inputPanel.add(aField);
inputPanel.add(label2);
inputPanel.add(bField);
inputPanel.add(label3);
inputPanel.add(cField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(calculateButton);
JPanel resultPanel = new JPanel();
resultPanel.add(result);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(inputPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(resultPanel, BorderLayout.NORTH);
setContentPane(mainPanel);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double a = Double.parseDouble(aField.getText());
double b = Double.parseDouble(bField.getText());
double c = Double.parseDouble(cField.getText());
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
result.setText("The equation has no real roots.");
} else if (discriminant == 0) {
double root = (-b) / (2 * a);
result.setText("The equation has one root: " + root);
} else {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
result.setText("The equation has two roots: " + root1 + " and " + root2);
}
}
public static void main(String[] args) {
new QuadraticEquationSolver();
}
}
```
这个程序创建了一个名为“Quadratic Equation Solver”的窗口,该窗口包含三个文本框,用于输入a、b、c的值,以及一个“Calculate”按钮,用于计算方程的解,并将结果显示在标签中。
当用户单击“Calculate”按钮时,程序将从文本框中读取a、b、c的值,并计算方程的根。然后,程序将更新结果标签,以显示方程的根。如果方程没有实根,则结果标签将显示相应的消息。
希望这个程序可以满足您的需求。
阅读全文