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

Boolean method with an incorrect input

I’m a bit stuck on an exercice I have to make and I can’t figure out the best way to do it.

I have to make a method that asks a question and expects Y or N. So I thought I would make a boolean method to return true or false, but the problem is that it would also return false if the user puts something other than Y or N. If I’m not mistaken, a boolean method cannot return null.

I’m very new to java and I’m not very far in my course so this problem will probably have a very simple solution. I also tried looking for an answer but didn’t seem to find what I was looking for.

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

This is what I have with the boolean method but i’m not quite happy with it:

    public static boolean test() {
        Scanner sc = new Scanner(System.in);
        System.out.println("question");
        String reponse = sc.next();

            if (reponse.equalsIgnoreCase("Y")) {
                return true;
            }
            else if (reponse.equalsIgnoreCase("N")) {
                return false;
        }
            else {
                return false;
        }
    }

>Solution :

Going by your comment you want your program to ask for input again if the input is neither "y" nor "n". You can achieve that behavior by adding an extra loop:

public static boolean test() {
    Scanner sc = new Scanner(System.in);
    System.out.println("question");
    String response = sc.next();

    while(!response.equalsIgnoreCase("Y") && !response.equalsIgnoreCase("N")) {
        // loop as long as input is neither "y" nor "n" (ignoring case)
        System.out.println("Please enter 'y' or 'n'");
        reponse = sc.next();
    }
    // if the loop is done input has to be either "y" or "n" at this point
    return reponse.equalsIgnoreCase("y");
}
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