Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
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);
2 Answers
+ 5
Use equals method to compare with string
if (!searchChoice.equals("y"))
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;
}