java

Reading a single char in Java


How can a char be entered in Java from keyboard?


Solution

  • 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();