Why is ((ans! = 'N') || (ans! = 'Y')) always true?

I am trying to get the user to rotate again and the "while" expression always returns false ... Anyone have any ideas?

reSpin = false;
if (reSpin == false){
    System.out.println("Would you like to spin again? Y/N");
    char ans = in.next().charAt(0);
   if (ans == 'Y'){
       reSpin =true;

   }else if (ans == 'N'){
       System.out.println("Thank you for playing!");
   }else {
       while ((ans != 'N') || (ans != 'Y')) {
           System.out.println("Invalid answer, please only enter Y/N");
           System.out.println("Would you like to spin again? Y/N");
           ans = in.next().charAt(0);
       }
   }


}

      

+3


source to share


4 answers


You probably want to use:

   while ((ans != 'N') && (ans != 'Y')) {

      



This checks that it is ans

not N and not Y. If you use ||

(or) there, then it will check that it is ans

either not N or not Y (which is true for any value ans

).

+5


source


Quite simply: according to your relative, ans

should be Y

, and N

at the same time.



+4


source


||

returns true if any of the expressions on both sides are true.

If ans

- Y

, then ans != 'N'

true, so the whole expression is (ans != 'N') || (ans != 'Y')

true. If ans

- N

, then ans != 'Y'

true, so the whole expression is true.

You want (ans != 'N') && (ans != 'Y')

one that says " ans

not 'N'

and ans

also not 'Y'

."

+2


source


ans

cannot be both "N" and "Y", so it is always either not equal to "N" or not equal to "Y". You can change it to:

while ((ans != 'N') && (ans != 'Y'))

      

This ensures that it is not equal to "N" and not equal to "Y".

+1


source







All Articles