编写一个应用程序,在窗口输入a,b,c三个数值,实现ax*x+bx+c=0的求解,并最终的求解的结果在窗口显示出来
时间: 2024-03-15 09:47:03 浏览: 62
c代码-求ax平方+bx+c+=0
5星 · 资源好评率100%
以下是Java代码实现应用程序,在窗口输入a、b、c三个数值,实现ax*x+bx+c=0的求解,并最终的求解的结果在窗口显示出来:
```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 final JLabel labelA, labelB, labelC, labelResult;
private final JTextField txtA, txtB, txtC;
private final JButton btnCalculate, btnReset;
public QuadraticEquationSolver() {
setTitle("Quadratic Equation Solver");
setSize(350, 200);
setLayout(new GridLayout(4, 2));
labelA = new JLabel("Enter a:");
txtA = new JTextField();
add(labelA);
add(txtA);
labelB = new JLabel("Enter b:");
txtB = new JTextField();
add(labelB);
add(txtB);
labelC = new JLabel("Enter c:");
txtC = new JTextField();
add(labelC);
add(txtC);
btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(this);
add(btnCalculate);
btnReset = new JButton("Reset");
btnReset.addActionListener(this);
add(btnReset);
labelResult = new JLabel("", JLabel.CENTER);
add(labelResult);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCalculate) {
try {
double a = Double.parseDouble(txtA.getText());
double b = Double.parseDouble(txtB.getText());
double c = Double.parseDouble(txtC.getText());
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
labelResult.setText("No real roots");
} else if (discriminant == 0) {
double x = -b / (2 * a);
labelResult.setText("The root is: " + x);
} else {
double x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double x2 = (-b - Math.sqrt(discriminant)) / (2 * a);
labelResult.setText("The roots are: " + x1 + " and " + x2);
}
} catch (NumberFormatException ex) {
labelResult.setText("Invalid input");
}
} else if (e.getSource() == btnReset) {
txtA.setText("");
txtB.setText("");
txtC.setText("");
labelResult.setText("");
}
}
public static void main(String[] args) {
new QuadraticEquationSolver();
}
}
```
该程序使用了 Java 的图形用户界面(GUI),通过继承 JFrame 类并实现 ActionListener 接口来实现用户输入和事件处理。用户可以在窗口中输入 a、b、c 三个数值,然后点击“Calculate”按钮来计算方程的根,并将计算结果显示在窗口中。如果用户需要重新输入值,可以点击“Reset”按钮清空输入框。
阅读全文