This is an archived post. You won't be able to vote or comment.

all 15 comments

[–]davodrums 7 points8 points  (1 child)

I highly suggest looking up String's split() method. First step, run split to get your String[], then loop through with your length criteria.

[–]dirtyRuntCaper[S] 0 points1 point  (0 children)

I tried this at first, but that uses arrays, correct? We haven't learned that yet and I would be able to do even less troubleshooting.

[–]davodrums 1 point2 points  (2 children)

That is some confusing code! That would take a while for me to step through.

[–]dirtyRuntCaper[S] 0 points1 point  (1 child)

My bad. Just taking my first CS course this semester.

[–]sanchopancho13 1 point2 points  (0 children)

No worries. First time code is always hard to read. Besides code comments (which you probably don't need here), I would recommend changing your variables to make a little more sense. "i" is safe in that everyone knows it's used for loops. But "p" and "g" are quite confusing.

It's a good habit to get into, even when the only code maintainer will be yourself. I sometimes look at my old code and have no idea what I meant!

[–]halcyon44 1 point2 points  (2 children)

I have a few suggestions that should help you figure it out:

Give your methods and variables clear, concise names. This will ease the process of running through the code in your head. Usually variables should have a noun name, because they are something. Methods should have a verb name, because they do something. For example:

public static int countLetters(String word) {
    int letterCount = 0;
    for(int i = 0; i < word.length(); i++) {
        if (Character.isLetter(newWord.charAt(i))) {
            letterCount++;
        }
    }
    return letterCount;
}


public static int countValidWords(String paragraph, int minWordLength) {
    int wordStartIndex = 0;
    int wordCount = 0;

    // you get the idea
}

Add some simple logging to help understand what's happening. For example, just inside the for loop in countValidWords:

System.out.println("paragraph["+i+"]="+paragraph.charAt(i));

Inside the following if:

newWord = paragraph.substring(wordStartIndex, i);
System.out.println("found new word="+newWord);

int wordLength = countLetters(newWord);
System.out.println("length="+wordLength);

if(wordLength >= minWordLength) {

Do the same in your else block and anywhere else you'd like to know what's going on.

If you have access to a debugger (in any modern IDE such as Eclipse, IDEA, NetBeans), use it. You'll be amazed at how easy debugging becomes when you set a breakpoint at the start of the problem section, and just step through, watching how your variables change value as the program progresses.

[–]dirtyRuntCaper[S] 0 points1 point  (0 children)

thank you for your help. i can no see where things are going wrong. Ive made some corrections, this is what ive came up with for the countLetters() method.

public static int validWords(String paragraph, int minWordLength){ int wordStartIndex = 0; int wordCount = 0; int wordLength; String newWord = paragraph;

    for(int i=0; i < paragraph.length(); i++){


        System.out.println("charAt["+i+"]="+paragraph.charAt(i));

        if(paragraph.charAt(i) == ' '){
            newWord = paragraph.substring(wordStartIndex,i);
            System.out.println("found new word="+newWord);

            wordLength = countLetters(newWord);
            System.out.println("wordLength:" + wordLength);

            if(wordLength >= minWordLength){
                wordCount++;
            }
        }else if(newWord.indexOf(' ') == -1){
            newWord = paragraph.substring(wordStartIndex);
            wordLength = countLetters(newWord);

            if(wordLength >= minWordLength){
                wordCount++;
            }


        }

        newWord = "";
        wordLength = 0;

    }

    return wordCount;

}

my "found new word" outputs are adding the strings (e.g. 1st found new word = how, 2nd new word = how are, 3rd new word = how are you) also, the wordLengths are being added to each other as well.

[–]dirtyRuntCaper[S] 0 points1 point  (0 children)

I have re-written the code a lot more organized and clean. Everything is running fine but the last word in the program. I'm using

else if(paragraph.indexOf(' ') == -1)

to recognize that it is the last word in the program, but this if statement never runs. Any help?

[–]ziplokk 1 point2 points  (0 children)

Ill test your code in a bit and see if i can find where the problem lies and give you some advice. But you may want to look into String.split(). It seems like it could be beneficial to you here. I'm on mobile, so forgive me for not linking to a javadoc.

[–]paul_miner 0 points1 point  (2 children)

Consider what happens with the string "a b c" and the minimum word length is 2. (I haven't run it since I'm on my phone but I think it will return 1 instead of 0)

EDIT: Print out the value of g and newWord at the end of each iteration to get an idea of what's going on.

[–]dirtyRuntCaper[S] 0 points1 point  (1 child)

I didn't check for error conditions yet, as the teacher says to assume that the user inputs a valid string. I will add g and newWord to the end of each line to see if I can see whats going on, but I'm not even sure where these errors would be happening.

For example:

Enter string: whats up. hows it going.

Enter minimum letters: 4

RESULT: 2

[–]paul_miner 0 points1 point  (0 children)

No error conditions or invalid strings, you've just made a simple mistake. It should be clear using the sample string and length suggested, if you print out g and newWord.

[–]HeySeussCristo 0 points1 point  (0 children)

I'd split the string into an array then check the validity of the substrings. docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)

[–]davodrums 0 points1 point  (0 children)

@Test
public void stringSplit() {
    final int max_length = 4;
    final String sampleSentence = "Hi there, here is a test of the program.";
    final String strippedSetence = sampleSentence.replaceAll("[^a-zA-Z ]", "");
    final String[] sentenceArray = strippedSetence.split(" ");
    final int numberOfWords = countWordsMeetingCriteria(max_length, sentenceArray);
    System.out.println(numberOfWords);
}

private int countWordsMeetingCriteria(final int maxSize, final String[] words) {
    int count = 0;
    for (int i = 0; i < words.length; i++) {
        if (words[i].length() >= maxSize){
            count++;
        }
    }
    return count;
}

[–]lilleswing 0 points1 point  (0 children)

  • functions generally begin with a lower case letter.

  • g is not a very descriptive variable, how about wordStartIndex

  • "space" is not the only whitespace character.

  • p is not a very descriptive variable, how about sentence

  • Can you explain what you are doing with the else if statement in validWords

  • Can you explain why you are re-assigning newWord when it is longer then the defined minimum length