Applied Programming/Strings/Java
strings.java
edit/**
* This program counts words in entered strings.
*
* Input:
* Text string
*
* Output:
* Word count
*
* Example:
* Enter a string or press <Enter> to quit:
* The cat in the hat.
* You entered 5 words.
*
* Enter a string or press <Enter> to quit:
* ...
*
* References:
* None
*/
import java.util.Scanner;
/**
* Runs main program logic.
*/
class Main {
public static void main(String[] args) {
try {
while (true) {
String text = getText();
System.out.println(String.format(
"You entered %d words.\n",
countWords(text)));
}
}
catch (Exception exception) {
System.out.println("Unexpected error.");
exception.printStackTrace();
System.exit(1);
}
}
/**
* Gets text string.
*
* @return Text string entered.
*
* Exits:
* If no string is entered.
*/
private static String getText() {
System.out.println("Enter a string or press <Enter> to quit:");
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
if (text.isEmpty()) {
System.exit(0);
}
return text;
}
/**
* Counts words in text.
*
* @param text
* @return count of words in text
*/
private static int countWords(String text) {
String SEPARATORS = " ~`!@#$%^&*()-_=+{}[]|\\:;\"'<>,.?/";
int wordCount = 0;
boolean inWord = false;
for (int i = 0; i < text.length(); i++) {
if (!inWord && !SEPARATORS.contains(text.substring(i, i + 1))) {
wordCount += 1;
inWord = true;
}
else if (inWord && SEPARATORS.contains(text.substring(i, i + 1))) {
inWord = false;
}
}
return wordCount;
}
}
Try It
editCopy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.