Answer to Question #309955 in Java | JSP | JSF for Lundi

Question #309955

Create a java program that will count all words in a sentence.THe program should have a minimum of two classes


1
Expert's answer
2022-03-11T11:53:12-0500


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();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS