Create a java program that will count all words in a sentence.THe program should have a minimum of two classes
import java.util.*;
class WordsCounter {
private String sentence;
public WordsCounter() {
}
public WordsCounter(String sentence) {
this.sentence = sentence;
}
public int countWords() {
return this.sentence.split("[ .,]+!?").length;
}
/**
* @return the sentence
*/
public String getSentence() {
return sentence;
}
/**
* @param sentence the sentence to set
*/
public void setSentence(String sentence) {
this.sentence = sentence;
}
}
class App {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String sentence = keyboard.nextLine();
WordsCounter wc = new WordsCounter(sentence);
System.out.println("The total words in the sentence: " + wc.countWords());
keyboard.close();
}
}
Comments
Leave a comment