不需要实现如果用户输入了非整数,我们会弹出一个错误对话框来提示用户。最后,我们将输入文本框的文本清空以便下一次输入
时间: 2024-02-27 19:52:10 浏览: 28
好的,以下是不包含上述功能的实现代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame {
private JTextField inputField;
private JTextField resultField;
private int sum;
private int count;
public Calculator() {
super("计算");
setLayout(new FlowLayout());
inputField = new JTextField(15);
inputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int num = Integer.parseInt(inputField.getText());
sum += num;
count++;
double avg = (double) sum / count;
resultField.setText("总和:" + sum + " 平均值:" + avg);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
inputField.setText("");
}
});
add(inputField);
resultField = new JTextField(15);
resultField.setEditable(false);
add(resultField);
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
}
```
在这个实现中,我们只是将输入文本框中的文本转换为整数,如果转换失败(即输入的不是整数),我们只是打印一个堆栈跟踪,而不是弹出一个错误对话框。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)