As per the requirement i have restricted the sentence word count
to less than 10 at split() method . Check the codes and let me know.
Solution 1: All elements take at a time from console
import java.util.Scanner;
public class CBIPin {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String[] s=new String[4];
int sum=0;
for(int i=0;i<s.length;i++)
{
String st=sc.nextLine();
String[] str=st.split("\\s",9);
if(st.equals(""))
{
System.out.print("0");
}
else
{
for(String w:str)
{
sum=sum+1;
}
System.out.print(sum);
sum=0;
}
}
}
}
Solution 2 : Take each element from console and print the output once
import java.util.Scanner;
public class CBIPin2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] str = new String[4];
int sum=0;
for (int i = 0; i < str.length; i++)
{
str[i]=s.nextLine();
}
for(int i=0; i<str.length;i++)
{
String[] str2=str[i].split("\\s", 9);
if(str[i].equals(""))
{
System.out.print("0");
}
else
{
for(String w:str2)
{
sum=sum+1;
}
System.out.print(sum);
sum=0;
}
}
}
}
2