The Scanner
class has methods to accept numeric (int
/double
) and String
input. There is no method to accept input of a char
.
Accepting char
input
Scanner fromKeyboard = new Scanner(System.in);
System.out.print("First letter of first name: ");
char firstInitial = fromKeyboard.nextLine().charAt(0);
System.out.print("First letter of last name: ");
char lastInitial = fromKeyboard.nextLine().charAt(0);
fromKeyboard.close();
System.out.println("First initial: " + firstInitial);
System.out.println("Last initial: " + lastInitial);
nextLine
is used to accept String
input. charAt
is used to obtain the first character of the input as a char
.
See Working with String objects for more details about charAt
and other String
methods.
This approach works if the user actually enters a single character in response to each prompt. If the user enters more than 1 character in response to a prompt, the code silently ignores the remaining characters. If the user enters 0 characters in response to a prompt (just presses enter), the call to charAt
crashes with a StringIndexOutOfBoundsException
.
Accepting and validating char
input
The example below assumes that fromKeyboard
has been declared and initialized as a Scanner
reading from the keyboard.
System.out.print("Enter a lowercase letter: ");
String response = fromKeyboard.nextLine();
while(response.length() != 1 ||
response.charAt(0) < 'a' ||
response.charAt(0) > 'z')
{
System.out.println("\nInvalid input");
System.out.print("Enter a lowercase letter: ");
response = fromKeyboard.nextLine();
}
System.out.println("Letter: " + response.charAt(0));
This is a standard input validation loop. The while
condition evaluates to true
when the input is not valid. The order of the expressions is important. Checking response.length() != 1
first ensures that charAt
will not be called if the user enters 0 characters.
See Input validation and Input validation as String for more details on the technique.