Reputation: 23
I have been trying to create a program in Java that outputs each word found in a string and the number of times they appear. I have been trying to do this without using any arrays or hashmap, and by only using string manipulation methods and string tokenizer, but I can't seem to wrap my head around the logic.
Here is what I have so far.
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
}
The output I am currently receiving is (the first word entered)=0.
Any help or advice with this or anything to lead me in the right direction?
Upvotes: 2
Views: 1295
Reputation: 1129
You are quite close. But the 0
as result does not match your posted code, it is 1
, but even if there are more occurrences. That is because you used ==
instead of .equals()
in the if
.
And in the end of the loop the tokenizer has been drained by the inner loop, so you should reinitialize a new one, espacially after you already changed the input
string.
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);
}
Note: As Andreas and coolioasjulio mentioned is the use of StringTokenizer
discouraged (more about it here).
Upvotes: 2