Home > Software design >  How do you check if the user input is a single Char
How do you check if the user input is a single Char

Time:05-06

I'm trying to have that if a single Character is entered(Ex: 'a', 'b') it returns and displays True, but if multiple are entered it returns and displays false(Ex: 'adf', 'a f e s').

import java.util.*;

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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