Search code examples
javainputcharjava.util.scanner

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

  • 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");
            }
        }
    }