我试图让它按升序打印出文本文件中的所有单词。当我运行它时,它会按升序打印出来,但它只打印一次出现的单词。我希望它打印出每个出现的单词(想要重复)。我不确定我做错了什么。另外我希望它只打印出单词而不是文本文件中的标点符号。我知道我需要使用“拆分”,只是不确定如何正确使用它。我以前用过一次,但不记得如何在这里应用它。
这是我到目前为止的代码:
public class DisplayingWords {
public static void main(String[] args) throws
FileNotFoundException, IOException
{
Scanner ci = new Scanner(System.in);
System.out.print("Please enter a text file to open: ");
String filename = ci.next();
System.out.println("");
File file = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String str;
while((str = br.readLine())!= null)
{
/*
* This is where i seem to be having my problems.
* I have only ever used a split once before and can not
* remember how to properly use it.
* i am trying to get the print out to avoid printing out
* all the punctuation marks and have only the words
*/
// String[] str = str.split("[ \n\t\r.,;:!?(){}]");
str.split("[ \n\t\r.,;:!?(){}]");
sb.append(str);
sb.append(" ");
System.out.println(str);
}
ArrayList<String> text = new ArrayList<>();
StringTokenizer st = new StringTokenizer(sb.toString().toLowerCase());
while(st.hasMoreTokens())
{
String s = st.nextToken();
text.add(s);
}
System.out.println("\n" + "Words Printed out in Ascending "
+ "(alphabetical) order: " + "\n");
HashSet<String> set = new HashSet<>(text);
List<String> arrayList = new ArrayList<>(set);
Collections.sort(arrayList);
for (Object ob : arrayList)
System.out.println("\t" + ob.toString());
}
}