Collin H.
Collin H.

Reputation: 23

Using while loops to validate input

I want to make the user enter only "y" "Y" "n" or "N". The resulting code asks the user to enter Y or N when they have entered the correct input, the opposite of what I expected by placing the ! in front of input.equalscaseignore(input).


import java.util.Scanner;


class inputVal {

    public static void main(String[] args) {
        String Input;
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter Y or N. ");
        Input = keyboard.nextLine();

        while (!Input.equalsIgnoreCase("Y") || !Input.equalsIgnoreCase("N"))
        {
            System.out.println("Please enter Y or N");
            Input = keyboard.nextLine();

        }


        keyboard.close();
    }

}

Upvotes: 1

Views: 1617

Answers (5)

RunFranks525
RunFranks525

Reputation: 163

Here is great tool to trace your code with: http://cscircles.cemc.uwaterloo.ca/java_visualize/#

Upvotes: 0

ajb
ajb

Reputation: 31699

To elaborate on @gtgaxiola's answer:

!Input.equalsIgnoreCase("Y") || !Input.equalsIgnoreCase("N")

Suppose Input is "Y". The left operand of || is false, since Input equals "Y". But the right operand is true, since Input is not equal to "N". And false || true is true, since the result of || is true whenever either operand is true. In fact, this expression is always going to be true no matter what Input is.

That's why you need to use &&:

!Input.equalsIgnoreCase("Y") && !Input.equalsIgnoreCase("N")

because you want the result to be true only if both equalsIgnoreCase calls return false.

Alternatively, you could say

! (Input.equalsIgnoreCase("Y") || Input.equalsIgnoreCase("N"))

See also this article on DeMorgan's Laws.

(By the way, the convention in Java is to use names starting with lower-case letters for variables, i.e. input.)

Upvotes: 2

sfedak
sfedak

Reputation: 676

Your boolean logic is what's killing you here

while (!Input.equalsIgnoreCase("Y") || !Input.equalsIgnoreCase("N"))

You want to be in the loop while the input is not Y AND not N, therefore you need to change it to

while (!Input.equalsIgnoreCase("Y") && !Input.equalsIgnoreCase("N"))

Upvotes: 1

Larry
Larry

Reputation: 93

My code logic is rusty but I believe that the issue is in the || operand.

One of the answers will always be FALSE therefor it won't enter the loop correctly.

Upvotes: 0

gtgaxiola
gtgaxiola

Reputation: 9331

It is your or condition, you must change it to and

while (!Input.equalsIgnoreCase("Y") && !Input.equalsIgnoreCase("N"))

Just reading it out loud would help understand the logic:

WHILE Input doesn't equal (ignore case) "Y" AND Input doesn't equal (ignore case) "N"

Upvotes: 6

Related Questions