Friday, February 27, 2009

Java Problem 25

So I picked the last problem first. And here's my take...

/**
* 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);
}
}

No comments: