可以用java使用列表框、组合框和菜单组件制作一个算术运算器示例吗。要求可以输入五个数据,第一行为初始数据,下面四行为均可输入数据并可自由选择“+-*/”四个符号来参与运算,最后一行用“=”符号来运算结果。四行运算符没有优 先级,按照顺序运算。增加要求:①采用文本行数组,操作数个数为5个②解决除数为 0的问题③区分“/”为整数除或实数除
时间: 2024-02-22 09:58:32 浏览: 60
好的,下面是一个简单的Java算术运算器示例,使用了列表框、组合框和菜单组件:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ArithmeticCalculator extends JFrame implements ActionListener {
private static final int WIDTH = 500;
private static final int HEIGHT = 350;
private JTextField[] inputFields = new JTextField[5];
private JComboBox<String>[] operatorBoxes = new JComboBox[4];
private JTextField resultField = new JTextField();
private JButton calculateButton = new JButton("Calculate");
public ArithmeticCalculator() {
setTitle("Arithmetic Calculator");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel inputPanel = new JPanel(new GridLayout(5, 2));
inputPanel.add(new JLabel("Input 1:"));
inputFields[0] = new JTextField();
inputPanel.add(inputFields[0]);
for (int i = 1; i < 5; i++) {
inputPanel.add(new JLabel("Input " + (i + 1) + ":"));
inputFields[i] = new JTextField();
inputPanel.add(inputFields[i]);
}
getContentPane().add(inputPanel, BorderLayout.NORTH);
JPanel operatorPanel = new JPanel(new GridLayout(4, 2));
for (int i = 0; i < 4; i++) {
operatorPanel.add(new JLabel("Operator " + (i + 1) + ":"));
operatorBoxes[i] = new JComboBox<>(new String[]{"+", "-", "*", "/", "÷"});
operatorBoxes[i].addActionListener(this);
operatorPanel.add(operatorBoxes[i]);
}
getContentPane().add(operatorPanel, BorderLayout.CENTER);
JPanel resultPanel = new JPanel(new GridLayout(1, 2));
resultPanel.add(new JLabel("Result:"));
resultField.setEditable(false);
resultPanel.add(resultField);
getContentPane().add(resultPanel, BorderLayout.SOUTH);
calculateButton.addActionListener(this);
getContentPane().add(calculateButton, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == calculateButton) {
double result = Double.parseDouble(inputFields[0].getText());
for (int i = 0; i < 4; i++) {
String operator = (String) operatorBoxes[i].getSelectedItem();
double operand = Double.parseDouble(inputFields[i + 1].getText());
switch (operator) {
case "+":
result += operand;
break;
case "-":
result -= operand;
break;
case "*":
result *= operand;
break;
case "/":
case "÷":
if (operand == 0) {
JOptionPane.showMessageDialog(this, "Division by zero error!");
return;
}
result /= operand;
break;
}
}
resultField.setText(Double.toString(result));
}
}
public static void main(String[] args) {
ArithmeticCalculator calculator = new ArithmeticCalculator();
calculator.setVisible(true);
}
}
```
在这个示例中,我们使用了`JTextField`来接收用户输入的数值,使用`JComboBox`来选择运算符,使用`JButton`来触发运算操作。在运算过程中,我们使用一个`switch`语句来根据运算符进行相应的运算,需要注意除数为0的情况。
希望这个示例能够帮助你理解如何使用Java的Swing组件库来构建算术运算器。
阅读全文