Write code which takes a sentence as an input from the user and then prints the length of the first word in that sentence. Hint #1: think about how you know where the first word ends - you may assume that the sentence contains more than one word. Hint #2: To make your life easier, use a string method that utilizes space. It looks kind of looks like this: String.method(" "). Sample run 1: Enter a sentence: Everything in its right place 10 Sample run 2: Enter a sentence: Down is the new up

in java

1 answer

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:

  1. Scanner: We use a Scanner object to read user input.
  2. Input Prompt: The user is prompted to enter a sentence.
  3. Split Method: The sentence is split into an array of words using the split(" ") method, which separates the string at each space.
  4. First Word: We access the first element of the array words[0], which corresponds to the first word of the input sentence.
  5. 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!