The program asks for string input, then a minimum word length input. If the word is less than the minimum word length, it will not count. I'm trying to do the program without using split() or whatever every other post says to do for these problems.
I thought maybe I have to check the first word, last word, and then words in between. But I'm having trouble. I spent way too long on this and I can't figure it out.
IO is a different class used to input, output, etc.
public class WordCount {
public static void main(String[] args) {
int minLength;
System.out.println("Enter a string.");
String string=IO.readString();
String str1=string.toLowerCase(); //changes all characters in the string to lower case
String str=str1.trim(); //Trims all spaces in the end.
System.out.println("Enter minimum length for each word.");
minLength=IO.readInt();
int num=wordCount(str, minLength);
IO.outputIntAnswer(num);
}
public static int wordCount(String str, int minLength){ //Method that counts words.
int count=0;
// First Word
for(int i=0;i<str.length();i++){
if (str.charAt(i)==' '){
String firstWord=str.substring(0,i);
if (firstWord.length()>=minLength){
count++;
}
}
}
// Last Word
for (int i=str.length()-1;i>0;i--){
if(str.charAt(i)==' '){
String lastWord=str.substring(i, str.length()-1);
if(lastWord.length()>=minLength){
count++;
}
for (int j=0; j<i;j++){ //An attempt to find other words in between..does not work
if(str.charAt(j)==' '){
String word=str.substring(j+1, str.indexOf(' ', j+1));
if(word.length()>=minLength){
count++;
}
}
}
}
}
return count;
}
}
=and==and+,-,*,>,<,/, and after commas and before{and after;'. Code looks tacky and hard to read when it is all squished together like that. Difficult to maintain. I worked in a kernel group where you not only would not be allowed to put code in the repository that was badly formatted like that, but would get into trouble for even trying. Look up C beautifiers and formatters. You will not find a single standard that says what you're doing is acceptable in the broader community. If you ever want a job, learn to format it.split()or listen to any of the advice that was given in previous answers.java.util.regex.*classes, such asPatternandMatcherto do that and a whole lot more, vastly more efficiently. Those are worth spending the time mastering, because they'll save you huge amounts of time in the long run.