I want to exit the while loop when the user enters 'N' or 'n'. But it does not work. It works well with one condition but not two.
import java.util.Scanner;
class Realtor {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
char myChar = 'i';
while(myChar != 'n' || myChar != 'N'){
System.out.println("Do you want see houses today?");
String input = sc.next();
myChar = input.charAt(0);
System.out.println("You entered "+myChar);
}
}
}
Suppose in a while loop, you have two conditions, and any one needs to be true to proceed to the body, then in that case you can use the || operator between those two conditions, and in case you want both to be true, you can use && operator. By using if statements and logical operators such as &&, 11,!
Python While Loop Multiple ConditionsTo combine two conditional expressions into one while loop, you'll need to use logical operators. This tells Python how you want all of your conditional expressions to be evaluated as a whole.
It works well with one condition but not two.
The general syntax of a while loop in JavaScript is given below. Here, condition is a statement. It can consist of multiple sub-statements i.e. there can be multiple conditions. For as long as condition evaluates to true , the code written inside the while block keeps on executing.
You need to change ||
to &&
so that both conditions must be true to enter the loop.
while(myChar != 'n' && myChar != 'N')
Your condition is wrong. myChar != 'n' || myChar != 'N'
will always be true.
Use myChar != 'n' && myChar != 'N'
instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With