javajava.util.scanner

Is there a way to accept a single character as an input?


New to programming, so my apologies if this is dumb question.

When utilizing the Scanner class, I fail to see if there is an option for obtaining a single character as input. For example,

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String a = input.nextLine();
    }
}

The above code allows me to pull the next line into a string, which can then be validated by using a while or if statement using a.length() != 1 and then stored into a character if needed.

But is there a way to pull a single character instead of utilizing a string and then validating? If not, can someone explain why this is not allowed? I think it may be due to classes or objects vs primitive types, but am unsure.


Solution

  • You can use System.in.read() instead of Scanner

    char input = (char) System.in.read();
    

    You can also use Scanner, doing something like:

    Scanner scanner = new Scanner(System.in);
    char input = scanner.next().charAt(0);
    

    For using String instead of char, you can also to convert to String:

    Scanner scanner = new Scanner(System.in);
    String input = String.valueOf(scanner.next().charAt(0));