Reading a single char in Java

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

How can a char be entered in Java from keyboard?

8条回答
  •  感动是毒
    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.

提交回复
热议问题