java 将二元运算符算法表达式输入一个文本框,另一个文本框显示值
时间: 2023-12-14 15:18:13 浏览: 41
可以通过使用Java的GUI组件来实现将二元运算符算法表达式输入一个文本框,另一个文本框显示值的功能。以下是实现的步骤:
1. 导入相关的类:需要先导入JFrame、JPanel、JLabel、JTextField、JButton等相关的类。
2. 创建GUI界面:使用JFrame类创建一个GUI窗口,并在窗口上添加一个JPanel面板组件和两个JLabel、两个JTextField、一个JButton等组件。
3. 绑定事件监听器:使用ActionListener类绑定JButton按钮的事件监听器,当点击按钮时,从输入文本框中获取算法表达式,计算表达式的值并在输出文本框中显示结果。
4. 实现计算功能:使用Stack类实现二元运算符算法表达式的计算功能。
下面是一个简单的Java代码示例,实现了将二元运算符算法表达式输入一个文本框,另一个文本框显示值的功能:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JPanel panel;
private JLabel inputLabel, outputLabel;
private JTextField inputField, outputField;
private JButton calculateButton;
public Calculator() {
// 初始化GUI界面
panel = new JPanel(new GridLayout(3, 2));
inputLabel = new JLabel("输入算法表达式:");
inputField = new JTextField("");
outputLabel = new JLabel("结果:");
outputField = new JTextField("");
outputField.setEditable(false);
calculateButton = new JButton("计算");
calculateButton.addActionListener(this);
panel.add(inputLabel);
panel.add(inputField);
panel.add(outputLabel);
panel.add(outputField);
panel.add(calculateButton);
add(panel);
// 设置窗口属性
setTitle("二元运算符算法表达式计算器");
setSize(400, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// 计算按钮的事件监听器
public void actionPerformed(ActionEvent e) {
String input = inputField.getText();
if (input.isEmpty()) {
outputField.setText("");
return;
}
Stack<Integer> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= '0' && c <= '9') {
int num = 0;
while (i < input.length() && input.charAt(i) >= '0' && input.charAt(i) <= '9') {
num = num * 10 + (input.charAt(i) - '0');
i++;
}
i--;
operands.push(num);
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
while (!operators.empty() && hasPrecedence(operators.peek(), c)) {
operands.push(applyOperation(operators.pop(), operands.pop(), operands.pop()));
}
operators.push(c);
}
}
while (!operators.empty()) {
operands.push(applyOperation(operators.pop(), operands.pop(), operands.pop()));
}
outputField.setText(String.valueOf(operands.pop()));
}
// 判断运算符优先级
private boolean hasPrecedence(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// 进行运算
private int applyOperation(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
public static void main(String[] args) {
new Calculator();
}
}
```
此代码示例使用了Stack类来实现二元运算符算法表达式的计算功能。在实际开发中,可能需要根据具体的需求进行更改和优化。