Reading a Character

posted Jan 20, 2014, 12:35 AM by iman baqir   [ updated Jan 20, 2014, 12:35 AM by Karwan Jacksi ]

Sometimes you will want to read a single character from the keyboard. For example, your program might ask the user a yes/no question, and specify that he or she type Y for yes or N for no. The Scanner class does not have a method for reading a single character, however. The approach that we will use in this book for reading a character is to use the Scanner class's nextLine method to read a string from the Keyboard, and then use the String class's charAt method to extract the first character of the string. This will be the character that the user entered at the keyboard, I lere is an example:


String  input;                           // To hold a line of input

char     answer;                        // To hold a single character


/ / Create a Scanner object for keyboard input.

Scanner keyboard = new Scanner(;


/ / Ask the user a question.

System.out.print("Are you having fun? (Y=yes, H=no) ";

input = keyboard.nextLine();            // Get a line of input,

answer = input.charAt(0);                 // Get the first character.


The input variable references a String object. The last statement in this code calls the String class's charAt method to retrieve the character at position 0, which is the first character in the string. After this statement executes, the answer variable will hold the character that the user typed at the keyboard.