Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in WHILE loop

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);
        }
    }
}
like image 865
user547453 Avatar asked Jun 11 '12 23:06

user547453


People also ask

How do you add two conditions to a while loop?

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,!

Can I have 2 conditions in while loop Python?

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.

Can we use two conditions in while loop in Java?

It works well with one condition but not two.

Can you have multiple conditions in a while loop JavaScript?

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.


2 Answers

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')
like image 194
Nick Rolando Avatar answered Sep 29 '22 11:09

Nick Rolando


Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.

Use myChar != 'n' && myChar != 'N' instead

like image 28
toniedzwiedz Avatar answered Sep 29 '22 12:09

toniedzwiedz