Take a char input from the Scanner

前端 未结 22 2630
[愿得一人]
[愿得一人] 2020-11-22 05:16

I am trying to find a way to take a char input from the keyboard.

I tried using:

Scanner reader = new Scanner(System.in);
char c = reade         


        
22条回答
  •  花落未央
    2020-11-22 06:05

    There are three ways to approach this problem:

    • Call next() on the Scanner, and extract the first character of the String (e.g. charAt(0)) If you want to read the rest of the line as characters, iterate over the remaining characters in the String. Other answers have this code.

    • Use setDelimiter("") to set the delimiter to an empty string. This will cause next() to tokenize into strings that are exactly one character long. So then you can repeatedly call next().charAt(0) to iterate the characters. You can then set the delimiter to its original value and resume scanning in the normal way!

    • Use the Reader API instead of the Scanner API. The Reader.read() method delivers a single character read from the input stream. For example:

      Reader reader = new InputStreamReader(System.in);
      int ch = reader.read();
      if (ch != -1) {  // check for EOF
          // we have a character ...
      }
      

    When you read from the console via System.in, the input is typically buffered by the operating system, and only "released" to the application when the user types ENTER. So if you intend your application to respond to individual keyboard strokes, this is not going to work. You would need to do some OS-specific native code stuff to turn off or work around line-buffering for console at the OS level.

    Reference:

    • How to read a single char from the console in Java (as the user types it)?

提交回复
热议问题