Multiple conditions in WHILE loop

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

This question is tagged with java while-loop

~ Asked on 2012-06-11 23:55:17

The Best Answer is


23

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

while(myChar != 'n' && myChar != 'N')

~ Answered on 2012-06-11 23:58:32


1

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

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

~ Answered on 2012-06-11 23:58:59


Most Viewed Questions: