0

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;
   }
}
4
  • Put a space on both sides of = 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. Commented Apr 5, 2015 at 19:25
  • Checkout AStyle actually you want a Java-oriented equivalent, but the formatting is basically the same Commented Apr 5, 2015 at 19:26
  • Let's start by why you do not want to use split() or listen to any of the advice that was given in previous answers. Commented Apr 5, 2015 at 19:29
  • You can also use Java's java.util.regex.* classes, such as Pattern and Matcher to 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. Commented Apr 5, 2015 at 19:31

3 Answers 3

2

This should be enough:

public static int wordCount(String str, int min) {
    int count = 0;
    str = str.trim()+" ";
    for(int i=0, st=0; i<str.length(); i++) {
        if(str.charAt(i) != ' ') continue;
        if(i-st >= min) count++;
        st = i+1;
    }
    return count;
}  
Sign up to request clarification or add additional context in comments.

2 Comments

Despite the missing return statement, this code doesn't act the way it should.
If I do one word, the output is 1 regardless of min
1

Beside the fact that your code is kind of scrappy and inadequate, the main problem here is that your first FOR loop doesn't stop after finding the first word. In fact, in counts every word in the input string, minus 1.

There is the same problem in your second loop.

If you really want to do it this way, you should use the BREAK keyword, to stop the loops when necessary.

EDIT

This should work

public static int wordCount(String str, int minLength) {     //Method that counts words.
    int count = 0;

    for (int i = 0, wordLength = 0; i < str.length() + 1; i++) {
        if (i == str.length() || str.charAt(i) == ' ') {
            if (wordLength >= minLength) {
                count++;
            }
            wordLength = 0;
        } else {
            wordLength++;
        }
    }

    return count;
}

2 Comments

thanks this works, but how can I make it so that it won't count punctuations or numbers as words?
Then you should use regular expressions in the first if statement within the for loop.
0

Please try this. This takes care of extra spaces, leading, & also trailing spaces.

public class WordsCount {
   static String str = " I Love Java  for  its  oops  concepts  ";
   static int i;
   static int count = 0;

   public static int numOfWords(String str) {
   int length = str.length();
   for(i=0;i<length;) {
      if(str.charAt(i)!=' ') {
          while(str.charAt(i)!=' ') {
             i++;
             if(i>=str.length())
                break;
          }
          count = count+1;
      } else {
          i++;
      }
  }
  return count;
  }

  public static void main(String[] args) {
      count = numOfWords(str);
      System.out.println("Count of words is : "+count);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.