Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading