java学生四则运算系统图形
时间: 2023-09-28 10:03:45 浏览: 73
以下是一个简单的 Java 学生四则运算系统图形实现的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class ArithmeticGUI extends JFrame implements ActionListener {
private JLabel num1Label, num2Label, operatorLabel, resultLabel;
private JTextField num1Field, num2Field, operatorField, resultField;
private JButton submitButton;
public ArithmeticGUI() {
setSize(300, 200);
setTitle("学生四则运算系统");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
num1Label = new JLabel("数字1:");
num2Label = new JLabel("数字2:");
operatorLabel = new JLabel("运算符:");
resultLabel = new JLabel("结果:");
num1Field = new JTextField(10);
num2Field = new JTextField(10);
operatorField = new JTextField(10);
resultField = new JTextField(10);
resultField.setEditable(false);
submitButton = new JButton("计算");
submitButton.addActionListener(this);
JPanel panel = new JPanel(new GridLayout(5, 2));
panel.add(num1Label);
panel.add(num1Field);
panel.add(num2Label);
panel.add(num2Field);
panel.add(operatorLabel);
panel.add(operatorField);
panel.add(resultLabel);
panel.add(resultField);
panel.add(submitButton);
add(panel);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitButton) {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
String operator = operatorField.getText();
int result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
JOptionPane.showMessageDialog(this, "无效的运算符");
return;
}
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入整数");
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(this, "除数不能为零");
}
}
}
public static void main(String[] args) {
new ArithmeticGUI();
}
}
```
该程序使用了 Java 的 Swing GUI 库来创建一个简单的窗口,其中包含两个文本框和一个按钮。当用户输入数字和运算符并点击按钮时,程序会根据运算符计算结果并将其显示在另一个文本框中。在计算过程中,程序会检查用户输入的数字是否为整数,以及除数是否为零,并在必要时弹出错误消息框。
阅读全文