In Java, you can accomplish this task by using the split
method of the String
class to separate the words based on spaces. Here's how you could write the program:
import java.util.Scanner;
public class FirstWordLength {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
// Split the sentence into words
String[] words = sentence.split(" ");
// Get the first word
String firstWord = words[0];
// Print the length of the first word
System.out.println("Length of the first word: " + firstWord.length());
// Close the scanner
scanner.close();
}
}
Explanation:
- Scanner: We use a
Scanner
object to read user input. - Input Prompt: The user is prompted to enter a sentence.
- Split Method: The sentence is split into an array of words using the
split(" ")
method, which separates the string at each space. - First Word: We access the first element of the array
words[0]
, which corresponds to the first word of the input sentence. - Length Calculation: Lastly, we print the length of the first word using the
length()
method.
You can run this code, and it will behave as specified in your request!