Write code which takes a sentence as an input from the user and then prints the length of the first word in that sentence. JAVA*****
Sample run 1:
Enter a sentence:
Everything in its right place
10
Answers
- Write a code in java that takes a sentence as input from user and then prints the length of the first word in that sentence.
import java.util.*;
class StringProgram
{
public static void main(String s[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Sentence: ");
String str= sc. nextInt();
// trim the white spaces at the beginning and at the end.
str = str.trim();
int c=0;
int i=0;
while(str.charAt(i++)!=' ')
++c;
System.out.println("Length of the first word in the sentence is: "+c);
}
}
Here is the code.
import java.util.*;
class StringProgram
{
public static void main(String s[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Sentence: ");
String str= sc. nextInt();
// trim the white spaces at the beginning and at the end.
str = str.trim();
int c=0;
int i=0;
while(str.charAt(i++)!=' ')
++c;
System.out.println("Length of the first word in the sentence is: "+c);
}
}