π‘ Introduction:
In Java, taking input from the user is commonly done using the Scanner class from the java.util package. However, since Java doesn’t have a direct method to read a single character, we usually take a string input and extract its first character.
This program demonstrates how to take a character input from the user in Java.
π» Java Program:
// Java program to take character input from the user
import java.util.Scanner;
public class CharacterInputExample {
public static void main(String[] args) {
// Create Scanner object for taking input
Scanner sc = new Scanner(System.in);
// Ask the user to enter a character
System.out.print("Enter a character: ");
// Take input as a string and extract first character
char ch = sc.next().charAt(0);
// Display the entered character
System.out.println("You entered: " + ch);
// Close the scanner
sc.close();
}
}
⚙️ Explanation:
-
Scanner sc = new Scanner(System.in);
→ Creates a Scanner object to take input from the user. -
sc.next()
→ Reads the next token (word or letter) entered by the user. -
charAt(0)
→ Extracts the first character of the entered string. -
System.out.println()
→ Displays the character entered by the user.
π§ Example Output:
Enter a character: A
You entered: A
πͺ Tip:
If you want to handle multiple characters or strings, you can directly use sc.nextLine() to read the entire line.
Comments
Post a Comment