Home > front end >  Boolean method with an incorrect input
Boolean method with an incorrect input

Time:10-28

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.

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

CodePudding user response:

You need only one condition equalsIgnoreCase("Y"), result of its evaluation is basically the return value. All the if-statements in your code are redundant.

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

CodePudding user response:

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