0

This is what I have in my code

  char guess = Keyboard.readChar();

but the error message comes up as "The method readChar() is undefined for the type scanner" The scanner i have is Scanner keyboard = new Scanner (System.in). Why Is this wrong?

Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58
brownie45
  • 1
  • 1

3 Answers3

1

you need to use this

 char guess = keyboard.next().charAt(0);
Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58
smushi
  • 685
  • 5
  • 17
0

Scanner does not have a method to read a char. Fundamentally, System.in is a buffered stream. You can read a line,

while(keyboard.hasNextLine()) {
  String line = keyboard.nextLine();
  char[] chars = line.toCharArray(); // <-- the chars read.
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
0

You can trying using nextLine() which reads in a String of text.

char code = keyboard.nextLine().charAt(0);

charAt(0) takes in the first character of the received input.


Additional Note: If you want to convert user inputs to upper/lower case. This is especially useful.

You can chain String methods together:

char code1 = keyboard.nextLine().toUpperCase().charAt(0);    //Convert input to uppercase
char code2 = keyboard.nextLine().toLowerCase().charAt(0);    //Convert input to lowercase
char code3 = keyboard.nextLine().replace(" ", "").charAt(0); //Prevent reading whitespace
user3437460
  • 16,235
  • 13
  • 52
  • 96