/**
* 25.Write a Java class called CountWords, which defines
* a main() method that asks the user to
* enter a String s, and displays the number of words in s.
* A word is delimited by one or many space
* characters. You MUST NOT not use any of the methods defined in
* the String class other than
* charAt() and length(). In addition, you MUST NOT use the
* StringTokenizer class.
*
* @author obispo
*/
import javax.swing.*;
import java.text.*;
class CountWords {
public static void main( String[] args ) {
String s;
int words = 0, index, len, notspace = 0;
s = JOptionPane.showInputDialog(null, "Enter string:");
s += " ";
len = s.length();
for (index = 0; index < len; index++) {
if (s.charAt(index) != ' ') {
notspace = 1;
} else {
if (notspace == 1) words++;
notspace = 0;
}
}
JOptionPane.showMessageDialog(null, "Word Count: " + words);
}
}
All I ever wish is that you will gain something from the examples I wrote in this blog. If you have suggestions, questions, or have a much better way of doing it, please feel free to drop your comments so I may also learn from it and also those who are crawling around this blog. Examples here are mostly about Unix/Linux administration and programming which varies from C, C++, C#, Java, Shell Scripting, PHP to Python and I hope I can post more.
Friday, February 27, 2009
Java Problem 25
So I picked the last problem first. And here's my take...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment