简体   繁体   中英

Validating a inputted char variable. Do-while loop will not break

I have a method that checks if the user is a student, but I can't get it validate the conditions.

char custStud = '0';
Scanner input = new Scanner(System.in);

do{
       System.out.println("Are you a student? (Type Y or N): ");
       custStud = input.next().charAt(0);
       custStud = Character.toLowerCase(custStud);
  }
  while (custStud != 'y' || custStud != 'n');

When I fire up this program, it does not break the loop, even if 'y' or 'n' are entered. I suspect custStud might have accidentally changed types when changed to lowercase, but I'm not sure. How can I make this loop work properly?

while (custStud != 'y' || custStud != 'n') is always true, since custStud can't be equal to both 'y' and 'n'.

You should change the condition to:

while (custStud != 'y' && custStud != 'n')

You've mistaken here:

 while (custStud != 'y' || custStud != 'n');// wrong 
 while (custStud != 'y' && custStud != 'n');// correct

Try running this code:

        char custStud = '0';
        Scanner input = new Scanner(System.in);

        do{
            System.out.println("Are you a student? (Type Y or N): ");
            custStud = input.next().charAt(0);
            custStud = Character.toLowerCase(custStud);
        }
        while (custStud != 'y' && custStud != 'n');
        System.out.print("\n answer:"+custStud);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM