Salvatore Maruccio
Salvatore Maruccio

Reputation: 174

Comparing char variables in java

I would compare a char, but it actually doesn't work:

//...
System.out.print("PROCEED? (Y/N):\t");
line = in.nextLine();
ch = line.charAt(0);

while (ch != 'y' || ch != 'n' || ch != 'Y' || ch != 'N'){
    System.out.print("NON-VALID INPUT. TYPE Y-N:\t");

    line = in.nextLine();
    ch = line.charAt(0);
}
//...

On my terminal, as I press y or n, the result is:

PROCEED? (Y/N): y
NON-VALID INPUT. TYPE Y-N:  y
NON-VALID INPUT. TYPE Y-N:  Y
NON-VALID INPUT. TYPE Y-N:  n
NON-VALID INPUT. TYPE Y-N:  r
NON-VALID INPUT. TYPE Y-N:  d
...

Upvotes: 0

Views: 2997

Answers (3)

Mike
Mike

Reputation: 321

The condition is wrong. You have to put the "and" condition (&&), for only enter to that condition if the user type either except ('Y', 'y', 'N', 'n'). The code would be as follows:

    System.out.print("PROCEED? (Y/N):\t");
    Scanner in = new Scanner(System.in);
    String line=in.nextLine();
    Character ch=line.charAt(0);

    while(ch!='y' && ch!='n' && ch!='Y' && ch!='N'){
        System.out.print("NON-VALID INPUT. TYPE Y-N:\t");

        line=in.nextLine();
        ch=line.charAt(0);
    }

Hope this can help you.

Upvotes: 0

Marievi
Marievi

Reputation: 5001

You need to use && instead of || in your while loop.

Upvotes: 0

Eran
Eran

Reputation: 393781

Your condition is wrong. It should be :

while(ch!='y' && ch!='n' && ch!='Y' && ch!='N')

since the loop should continue as long as the input character is different than all 4 acceptable inputs.

Upvotes: 5

Related Questions