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
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();
}
}
Comments
Leave a comment