Take a char input from the Scanner
To take a character input from the Scanner in Java, you can use the next()
method to read a string and then use the charAt(int index)
method to get the first character of that string. Here's an example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
String input = scanner.next();
char c = input.charAt(0);
System.out.println("You entered: " + c);
}
}
Alternatively, you can use the nextLine()
method to read a full line of input as a string and then use the charAt(int index)
method to get the first character of that string. Here's an example:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
String input = scanner.nextLine();
char c = input.charAt(0);
System.out.println("You entered: " + c);
}
}
I hope this helps! Let me know if you have any other questions.