To input a single character in Java, you can use the Scanner
class or the BufferedReader
class.
Here is an example of how to use the Scanner
class to input a character:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a character: "); char c = sc.next().charAt(0); System.out.println("You entered: " + c); sc.close(); } }
In this example, the Scanner
class is used to read a line of input from the console. The next()
method is used to read the next token in the input as a String
, and the charAt()
method is used to extract the first character of the String
. The character is then printed to the console.
Here is an example of how to use the BufferedReader
class to input a character:
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a character: "); char c = (char) br.read(); System.out.println("You entered: " + c); br.close(); } }
In this example, the BufferedReader
class is used to read a single character from the console. The read()
method is used to read the next character in the input as an integer, and the value is cast to a char
type. The character is then printed to the console.
For more information on the Scanner
class and the BufferedReader
class in Java, you can refer to the Java documentation and the Java tutorial.