I am looking for a way to create a method with the initial state in while loop, which will count the length of each word in a string using I want the output to be something along the lines of:
hello world how are you
There are 0 words of length 0
There are 0 words of length 1
There are 0 words of length 2
There are 3 words of length 3
There are 0 words of length 4
There are 2 words of length 5
ithis is my code so far it sort of does the job but not the way i want it too
import java.util.Scanner;
import java.util.StringTokenizer;
public class Brown_Matthew_13117002{
public static int count(String s, int len){
int result=0;
StringTokenizer st=new StringTokenizer(s,"[ ,;]");
while(st.hasMoreTokens()){
if(st.nextToken().length()==len){
result++;
}
}
return result;
}
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String line ="";
int max = 6;
while((line=scan.nextLine())!=null){
String sentence [] = line.split(" ");
for(int i=0;i<sentence.length;i++) {
System.out.println(sentence[i]);
System.out.println("There are " + count(line, i) + " words of lenghth " + i);
}
}
}
}
the output would end up being
hello
There are 0 words of lenghth 0
world
There are 0 words of lenghth 1
how
There are 0 words of lenghth 2
are
There are 3 words of lenghth 3
you
There are 0 words of lenghth 4
i have no idea how to fix this any h help is appreciated as i am new to java.