wood burning stoves 2.0
The moose likes Beginning Java and the fly likes Count Words Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Count Words" Watch "Count Words" New topic

Count Words

Amy Lee

Joined: Nov 02, 2004
Posts: 25
I've written a method to count the number of words in a string. I realize there is probably a method in the Java Documentation library that could make this short and sweet, but our teacher isn't allowing us to use it. I compiled my code and received the error "operator || cannot be applied to char, char" - here is my code:

How else can I specify in my if statement that if i = to any of the characters listed in the parentheses, i is not a letter? Please help - thanks!
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
In Java, you can't say "if ( a == 6 || 7 || 8 ) ..."

You must say "if ( a == 6 || a == 7 || a == 8 ) ..."

Mike Gershman
SCJP 1.4, SCWCD in process
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
What you could do is

if(" \t\n.:;?!".indexOf(t.charAt(i)) != -1)

If you have any questions on what that does please post them, but if you look at the String API you should be able to figure it out.
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

Tip: If you try to write methods in such a way that it focuses on doing one thing, it will go a long way in making the problem easier to tackle and your code easier to write and read.

For example, your countWords method now does two things: it counts words and it checks if a character is a whitespace.

If you moved the logic that checks if a character is a whitespace to another method, you could write:

if (isWhiteSpace(ch)) {
} else {

This will tighten up the countWords method (formally, we say it makes the code more cohesive) and helps hide some of the implementation details that may be keeping you from seeing some of the flaws in your logic.

Here's another tip: the String class has a method that will return a char[]. You could iterate over this char[] instead of using the charAt(i) method.

Here's what your current logic reads like:

If you were given these instructions to perform, would it make sense to you?

One last tip: you are counting words, not whitespace. You need to keep track of when you're actually in a word. While you're in a word, watch out for whitespaces: this signals that you are done with the current word (now you can count it) and are either getting ready to start going through the next word or that there are no more words to count.

Junilu - [How to Ask Questions] [How to Answer Questions]
I agree. Here's the link: http://aspose.com/file-tools
subject: Count Words
It's not a secret anymore!