![](/img/trans.png)
[英]I can't seem to figure out how to display answers as words for my Calculator Project?
[英]I can't seem to figure out how to get this print out all the words including the duplicates
我試圖讓它以升序打印出文本文件中的所有單詞。 當我運行它時,它以升序打印出來,但它只打印出一個單詞。 我希望它打印出每個單詞的出現(需要重復)。 我不確定我做錯了什么。 此外,我希望它只打印出文字文件中的單詞而不是標點符號。 我知道我需要使用“拆分”,只是不確定如何正確使用它。 我之前曾經使用它,但不記得如何在這里應用它。
這是我到目前為止的代碼:
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());
}
}
你的副本可能在這里被刪除了
HashSet<String> set = new HashSet<>(text);
一set
通常不包含重復項,所以我只是對text
數組列表進行排序
Collections.sort(text);
for (Object ob : text)
System.out.println("\t" + ob.toString());
問題出在這里:
HashSet<String> set = new HashSet<>(text);
Set
不包含重復項。
您應該使用以下代碼:
//HashSet<String> set = new HashSet<>(text);
List<String> arrayList = new ArrayList<>(text);
Collections.sort(arrayList);
另外對於拆分方法,我建議你使用:
s.split("[\\s\\.,;:\\?!]+");
例如,考慮下面給出的代碼:
String s = "Abcdef;Ad; country hahahahah? ad! \n alsj;d;lajfa try.... wait, which wish work";
String sp[] = s.split("[\\s\\.,;:\\?!]+");
for (String sr : sp )
{
System.out.println(sr);
}
其輸出如下:
Abcdef
Ad
country
hahahahah
ad
alsj
d
lajfa
try
wait
which
wish
work
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.