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,633
  • 7
  • 33
  • 60
brownie45
  • 1
  • 2

3 Answers3

1

you need to use this

 char guess = keyboard.next().charAt(0);
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
smushi
  • 701
  • 6
  • 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
  • 198,278
  • 20
  • 158
  • 249
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
  • 17,253
  • 15
  • 58
  • 106