-2

Hello I know this is so basic but I am having trouble in comparing char specifically with the !=. Whenever I input other letter (not y and n) code still loop.

I tried changing the != to == and when i press Y it gets out of loop.

How is this happening? Thank you!

public static void main(String[] args) {
    char inputChar;
    Scanner input = new Scanner(System.in);

    do {
        System.out.println("-----------------------------------------------");
        System.out.println("Try Again(Y/N)? ");
        do {
            inputChar = input.next().toUpperCase().charAt(0);
            System.out.println("Loop");
        } while (inputChar != 'Y' || inputChar != 'N');
        System.out.println(inputChar + " d");
    } while (inputChar == 'Y');
    System.out.println("Thank you and Good bye!");
}
John Wink
  • 27
  • 4

2 Answers2

5
while (inputChar != 'Y' || inputChar != 'N');

The condition you wrote says 'loop while the input is not Y or is not N'.

No character is equal to Y and equal to N at the same time, so this will loop forever.

If it's Y, then it's not N, so the second part is true.

If it's N, then it's not Y, so the first part is true.

If it's Z, then both parts are true.

You want

while (inputChar != 'Y' && inputChar != 'N');
passer-by
  • 1,103
  • 2
  • 4
1

The issue is with this line: } while (inputChar != 'Y' || inputChar != 'N');

Since you are using a logical or operation, the loop continues while inputChar is not equal to Y or inputChar is not equal to N. The issue is that one of these is always true so your loop runs forever since a character cannot be both equal to 'N' and to 'Y'. Try using a logical and (&&) instead.

jamster02
  • 11
  • 4