5

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);
        }
    }
}

3 Answers 3

25

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

while(myChar != 'n' && myChar != 'N')
Sign up to request clarification or add additional context in comments.

5 Comments

You should also change it to a do-while loop so that you don't have to randomly initialize myChar.
Yeah, should definitely be a do-while
You can also do Character.toLowerCase(myChar) != 'n' to make it more readable.
this solved my problem. However, && means 'and'. This would mean both conditions have to be true. I am a PL-SQL developer and I find it difficult to understand this concept.
@user547453 If you use || then just one or the other condition can be true to enter the loop. If myChar = 'n' then myChar != 'n' is false, but myChar != 'N' is true, so it enters the loop. With && since the first condition would be false, it would not enter the loop.
1

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

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

Comments

0

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.