'How do you check if the user input is a single Char

I'm trying to write a program where if the user enters a single character, the program displays True on screen, otherwise if multiple characters are entered it prints False.

public class FinalExamTakeHome8 {
    public static void main(String[] args) {
        try (Scanner kbd = new Scanner(System.in)) {
            System.out.println("Enter an item");
            if (kbd.hasNextInt() || kbd.hasNextChar() || kbd.hasNextDouble()) {
                System.out.println("True");
            } else {
                System.out.println("False");
            }
        }
    }
}


Solution 1:[1]

You could use the nextLine() method to read the user input, regardless of being one or more characters. Then, once you've acquired the text, check whether its length is equals to 1 or not.

public static void main(String[] args) {
    try (Scanner kbd = new Scanner(System.in)) {
        System.out.println("Enter an item");
        String input = kbd.nextLine();
        if (input.length() == 1) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}

EDIT: For some reason, it does not incorporate the link properly in the text. I'll leave the link to the Scanner documentation here:

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Solution 2:[2]

You could use the scanner.nextLine() method to get the string, then just use the length() method to measure the size.

String line = kbd.nextLine();
System.out.println(line.length()==1); 

Because the comparison will result in a Boolean value you can just print it.

Solution 3:[3]

There is no dedicated API to check if the user has entered a single character, but can make use of Regex. I have tested it and is working perfectly fine for your use case.

public static void main(String[] args) {
    try (Scanner kbd = new Scanner(System.in)) {
        System.out.println("Enter an item");
        if (kbd.hasNextInt() || kbd.hasNext("^[a-zA-Z]") || kbd.hasNextDouble()) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jimboweb
Solution 3