使用java设计一个文本字频统计界面,要求可以统计各个字符的数目,界面内容还包括打开文件,计数,清除界面
时间: 2024-03-17 13:43:57 浏览: 17
好的,下面是一个简单的 Java 程序,实现了文本字频统计的界面,包括打开文件、计数、清除界面等功能。您可以参考以下代码:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class TextFrequencyCounter extends Frame implements ActionListener {
private TextArea textArea;
private Button openButton;
private Button countButton;
private Button clearButton;
private Label statusLabel;
private File file;
private int[] freq;
public TextFrequencyCounter() {
setTitle("Text Frequency Counter");
setSize(400, 300);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
textArea = new TextArea();
add(textArea, BorderLayout.CENTER);
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new FlowLayout());
openButton = new Button("Open File");
openButton.addActionListener(this);
buttonPanel.add(openButton);
countButton = new Button("Count");
countButton.addActionListener(this);
buttonPanel.add(countButton);
clearButton = new Button("Clear");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
add(buttonPanel, BorderLayout.NORTH);
statusLabel = new Label(" ");
add(statusLabel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
FileDialog fileDialog = new FileDialog(this, "Open Text File", FileDialog.LOAD);
fileDialog.setVisible(true);
if (fileDialog.getFile() != null) {
file = new File(fileDialog.getDirectory(), fileDialog.getFile());
statusLabel.setText("File opened: " + file.getName());
}
} else if (e.getSource() == countButton) {
if (file == null) {
statusLabel.setText("No file opened.");
} else {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
freq = new int[128];
int c;
while ((c = reader.read()) != -1) {
if (c < 128) {
freq[c]++;
}
}
reader.close();
updateTextArea();
statusLabel.setText("Count completed.");
} catch (IOException ex) {
statusLabel.setText("Error: " + ex.getMessage());
}
}
} else if (e.getSource() == clearButton) {
textArea.setText("");
statusLabel.setText(" ");
}
}
private void updateTextArea() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 128; i++) {
if (freq[i] > 0) {
buffer.append((char)i + " : " + freq[i] + "\n");
}
}
textArea.setText(buffer.toString());
}
public static void main(String[] args) {
TextFrequencyCounter frame = new TextFrequencyCounter();
frame.setVisible(true);
}
}
```
程序界面由一个文本区域、三个按钮和一个标签组成。用户可以点击“Open File”按钮打开一个文本文件,并在标签中显示文件名;点击“Count”按钮统计文件中各个字符出现的次数,并在文本区域中显示结果;点击“Clear”按钮清空文本区域和标签。
具体实现中,我们使用了 Java AWT 组件,通过继承 Frame 类和实现 ActionListener 接口来创建一个窗口程序。当用户点击按钮时,程序会响应相应的事件,从而执行相应的操作。在计数的过程中,我们首先打开文件并创建一个长度为 128 的整型数组 freq,用来记录每个字符出现的次数。然后逐个读取文件中的字符,将其转换成 ASCII 码,并将对应的 freq 数组元素加 1。最后,我们遍历 freq 数组,将每个非零元素输出到文本区域中。
希望这个程序可以帮助您完成任务!