支持此程序计算每个单词在.txt文件中显示的次数 我在正确的轨道上,因为这个程序在文本区域中显示文件中的每个单词,但我需要它不重复单词并增加计数器。我是否在每个词的正确轨道上:单词陈述?我知道我在这个声明中只需要一些逻辑,但我不确定如何实现它。我应该补充一点,我使用有序链接列表将所有单词按字母顺序排列在文本区域中,以便它们或者按顺序排列。
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
public class Oct29 extends JPanel
{
private OrderedList<String> words;
private String filename;
private int width = 800;
private int height = 600;
private TextArea textarea;
public Oct29()
{
Scanner scan;
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(width,height));
add(textarea);
JFileChooser chooser = new JFileChooser("../Text");
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
words = new OrderedLinkedList<String>();
while(scan.hasNext())
{
String token = scan.next().toLowerCase();
token = token.replace(",","").replace(".","");
words.add(token);
}
scan.close();
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
for(String word : words)
{
for( int i=0;i<words.size(); i++)
{
int x =0; // This does not work but I'm trying to find if I'm on the right track
if(x < words.size())
textarea.append(word+"\n"); // THIS BY ITESELF WITHOUT THE INNER FOR LOOP WORKS FINE FOR DISPLAYING THE WORDS IN A TEXT AREA.
x++;
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Oct 29");
frame.getContentPane().add(new Oct29());
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:0)
我建议尝试另一种技巧: How many times a word appears in a TXT file 这也许有用: Count the amount of times a string appears in a file
答案 1 :(得分:0)
您可以使用Map解决问题。它可以将您的键(在您的情况下是这些单词)映射到值(反映这些单词出现的整数值)。您可以按如下方式初始化地图:
Map<String, Integer> wordCount=new HashMap<String, Integer>();
在循环内部,您必须检查地图是否已包含该密钥(单词)。如果是这样,那么你必须增加与之关联的整数的值。如果未添加,只需将该对添加到地图中,并将整数值设置为1。