0

Conditional code not working

/*Hi. I'm trying to implement the execution of a line of code based on the condition that the variable 'searchChoice' is not equal to "y" and also not equal to "n", but even when the variable is not equal to either "y" or "n", the code still runs and "invalid input!!" gets displayed. The below is the problematic code. Your assistance is appreciated. "*/ do{ System.out.println("Enter \'y\' for \'yes\' and \'n\' for \'no\'"); searchChoice = s.nextLine().toLowerCase(); if((searchChoice != "y") & (searchChoice !="n")){ System.out.println("invalid input!!"); isCorrectInput=false; } } while(!isCorrectInput);

14th Mar 2022, 2:19 PM
Ayomisesebere
Ayomisesebere - avatar
2 Respuestas
+ 5
Use equals method to compare with string if (!searchChoice.equals("y"))
14th Mar 2022, 2:26 PM
A͢J
A͢J - avatar
0
Use equals() method for string equalence. searchChoice.equals("y") ; And & is a bitwise operator. Not logical. Use && instead.. edit: Ayomisesebere oh. but actually you need to use || (or) logical operator. try if( !(searchChoice.equals("y") || searchChoice.equals("n")) ) { System.out.println("Invalid input"); isCorrectInput = false; }
14th Mar 2022, 2:25 PM
Jayakrishna 🇮🇳