Answer to Question #290557 in Java | JSP | JSF for Stinger

Question #290557

Write a program to take a String as input then display number of words it has.

Use java.util.* package and charAt(),length(),trim() only.

The output must be like below:

Enter a String:

(black space) My name is Stinger (blank space)

Number of words is 4


1
Expert's answer
2022-01-25T09:00:11-0500


import java.util.*;


public class App {


	/**
	 * The start point of the program
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in);
		int numberWords = 1;
		System.out.println("Enter a String: ");
		String String = keyBoard.nextLine();
		String = String.trim();
		for (int i = 0; i < String.length(); i++) {
			if (String.charAt(i) == ' ') {
				numberWords++;
			}
		}
		System.out.println("Number of words is " + numberWords);


		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