[英]How do you create a word frequency counter in Java without hashmap or arrays?
我一直在嘗試用 Java 創建一個程序,該程序輸出在字符串中找到的每個單詞及其出現的次數。 我一直試圖在不使用任何數組或哈希圖的情況下,只使用字符串操作方法和字符串標記器來做到這一點,但我似乎無法理解邏輯。
這是我到目前為止所擁有的。
Scanner sc=new Scanner(System.in);
String input="";
int count=1;
String word="";
System.out.println("Enter your paragraph.");
input=sc.nextLine();
StringTokenizer st=new StringTokenizer(input);
while(st.hasMoreTokens()){
word=st.nextToken();
while(st.hasMoreTokens()){
if(st.nextToken()==word){
count++;
}
}
System.out.println(word+": "+count);
input=input.replaceAll(currentToken," ")
count=1
}
我目前收到的輸出是(輸入的第一個單詞)=0。
有什么幫助或建議可以引導我朝着正確的方向前進?
你很接近。 但是結果0
與您發布的代碼不匹配,它是1
,但即使出現次數更多。 那是因為您在if
使用了==
而不是.equals()
。
在循環結束時,標記器已被內部循環耗盡,因此您應該重新初始化一個新的,尤其是在您已經更改了input
字符串之后。
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens()) {
word = st.nextToken();
while (st.hasMoreTokens()) {
if (st.nextToken().equals(word)) {
count++;
}
}
System.out.println(word + ": " + count);
input = input.replaceAll(word, "");
count = 1;
st = new StringTokenizer(input);
}
注意:正如Andreas和coolioasjulio 所提到的,不鼓勵使用StringTokenizer
(更多信息請點擊此處)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.