Question is to find the number of words in a string entered by the user, below code give a correct output when there is only one whitespace between each word but fails when there is more than one whitespace between each word. Can anyone please help me to find out what is wrong with this code.?
CODE -
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String");
String str1 = sc.nextLine();
String str2 = str1.trim();
String strar[] = str2.split(" ");
int count = 0;
for(String s:strar)
{
if (!(s.equals(" ")))
{
count++;
}
}
System.out.println(count);
}}