I am practicing some exercises for my CS final, and am stuck on this problem, where I have to read a string, get a minimum length from the user, and return the amount of words that have at least that many letters. It seems as if my code is fine, but it can’t print out the answer. Can anyone help me out?
public class WordCount {
public static void main (String [] args) {
System.out.println("Enter a string: ");
String input = IO.readString();
System.out.println("Enter minimum word length");
int wordlength = IO.readInt();
int count = 0 ;
do {
for (int i = 0 ; i < input.length(); i ++) {
if (input.indexOf(i) == ' ') {
String check = input.substring(0, i);
if (check.length() >= wordlength) {
count++;
input = input.substring(i);
break;
}
}
}
} while (input.length() > 0);
System.out.print("Words longer than " + wordlength + " characters: " + count);
}
}
It seems as if the while loop runs infinitely, but I can’t figure out why!
Currently there are few problems with your code that I’ll point out first: –
In the above statement, you should use
String#charAtmethod, to get a character at a particular index.String#indexOfmethod is used for reverse process, i.e, you have a character and you want to find it’s index.Secondly, you are modifying your
inputinside theloop itself. And you are using the length ofinputin the terminating condition in theloop. You should not do anything like this.Rather, you can use another variable, which will store the index of last word you processed. And use that
indexin yoursubstringmethod.Thirdly, you don’t really need a
do whileloop here. Yourfor loopitself is iterating over all your characters. Just remove thebreakfrom yourif, which is really not required.So, your code will be modified to this: –
Now this was the modification of your code, so that you can learn what was your mistake.
However, you have a pretty easy way to get what you want. You can use
String#splitmethod tosplityour string onspace, which will return you an array of all the words, and you can operate on those words.It works something like this (in case you can use it): –