Write a JAVA program to read a String value from user and display its individual characters? | StudyEcart | CODE003


import java.util.Scanner; public class ReadAndDisplayCharacters { public static void main(String[] args) { // Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a string: "); // Read the user's input as a string String userInput = scanner.nextLine(); // Display individual characters of the entered string System.out.println("Individual characters:"); for (int i = 0; i < userInput.length(); i++) { System.out.println(userInput.charAt(i)); } // Close the scanner to release resources scanner.close(); } } (code-box)

In this program:

1. We import the `Scanner` class from the `java.util` package to handle user input.
2. We create a `Scanner` object named `scanner` to read input from the standard input stream (usually the keyboard).
3. We use the `System.out.print` method to display a prompt asking the user to enter a string.
4. We use the `scanner.nextLine()` method to read the entire line of text entered by the user, including spaces.
5. We then use a `for` loop to iterate through each character in the entered string using the `charAt` method.
6. Within the loop, we use the `System.out.println` method to display each individual character on a separate line.

Remember to import the necessary packages and handle resources properly by closing the `Scanner` when you're done using it.

Post a Comment

0 Comments