w3resource

Java: Capitalize the first letter of each word in a sentence

Java Basic: Exercise-58 with Solution

Write a Java program to capitalize the first letter of each word in a sentence.

Pictorial Presentation: Capitalize the first letter of each word in a sentence

Java Basic Exercises: Capitalize the first letter of each word in a sentence

Sample Solution:

Java Code:

import java.util.*;

public class Exercise58 {
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner in = new Scanner(System.in);
        System.out.print("Input a Sentence: ");
        
        // Read a sentence from the user
        String line = in.nextLine();
        
        // Initialize an empty string to store the result in uppercase
        String upper_case_line = "";
        
        // Create a Scanner to process individual words in the sentence
        Scanner lineScan = new Scanner(line);
        
        // Iterate through the words in the sentence
        while (lineScan.hasNext()) {
            String word = lineScan.next();
            
            // Capitalize the first letter of each word and append it to the result
            upper_case_line += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
        }
        
        // Remove trailing space and print the result in uppercase
        System.out.println(upper_case_line.trim());
    }
}

Sample Output:

Input a Sentence: the quick brown fox jumps over the lazy dog.         
The Quick Brown Fox Jumps Over The Lazy Dog.

Flowchart:

Flowchart: Java exercises: Capitalize the first letter of each word in a sentence

Java Code Editor:

Previous: Write a Java program to accepts an integer and count the factors of the number.
Next: Write a Java program to convert a given string into lowercase.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/basic/java-basic-exercise-58.php