Reading a single char in Java

后端 未结 8 752
暗喜
暗喜 2020-12-01 18:17

How can a char be entered in Java from keyboard?

相关标签:
8条回答
  • 2020-12-01 18:18

    .... char ch; ... ch=scan.next().charAt(0); . . It's the easy way to get character.

    0 讨论(0)
  • 2020-12-01 18:24

    Using nextline and System.in.read as often proposed requires the user to hit enter after typing a character. However, people searching for an answer to this question, may also be interested in directly respond to a key press in a console!

    I found a solution to do so using jline3, wherein we first change the terminal into rawmode to directly respond to keys, and then wait for the next entered character:

    var terminal = TerminalBuilder.terminal()
    terminal.enterRawMode()
    var reader = terminal.reader()
    
    var c = reader.read()
    
    <dependency>
        <groupId>org.jline</groupId>
        <artifactId>jline</artifactId>
        <version>3.12.3</version>
    </dependency>
    
    0 讨论(0)
  • 2020-12-01 18:27

    You can use a Scanner for this. It's not clear what your exact requirements are, but here's an example that should be illustrative:

        Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
        while (!sc.hasNext("z")) {
            char ch = sc.next().charAt(0);
            System.out.print("[" + ch + "] ");
        }
    

    If you give this input:

    123 a b c x   y   z
    

    The output is:

    [1] [2] [3] [a] [b] [c] [x] [y] 
    

    So what happens here is that the Scanner uses \s* as delimiter, which is the regex for "zero or more whitespace characters". This skips spaces etc in the input, so you only get non-whitespace characters, one at a time.

    0 讨论(0)
  • 2020-12-01 18:27

    i found this way worked nice:

        {
        char [] a;
        String temp;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("please give the first integer :");
        temp=keyboard.next();
        a=temp.toCharArray();
        }
    

    you can also get individual one with String.charAt()

    0 讨论(0)
  • 2020-12-01 18:35

    You can either scan an entire line:

    Scanner s = new Scanner(System.in);
    String str = s.nextLine();
    

    Or you can read a single char, given you know what encoding you're dealing with:

    char c = (char) System.in.read();
    
    0 讨论(0)
  • 2020-12-01 18:35

    Maybe you could try this code:

    import java.io.*;
    public class Test
    {
    public static void main(String[] args)
    {
    try
      {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String userInput = in.readLine();
      System.out.println("\n\nUser entered -> " + userInput);
      }
      catch(IOException e)
      {
      System.out.println("IOException has been caught");
      }
     }
    }
    
    0 讨论(0)
提交回复
热议问题