1

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?

3
  • 2
    while (custStud != 'y' || custStud != 'n'); always going to be true Commented Aug 10, 2017 at 6:57
  • @batPerson what will happen if N is pressed , do loop continue if user input N Commented Aug 10, 2017 at 7:00
  • @batPerson Have a look and upvote or accept answer if it helps Commented Aug 10, 2017 at 7:08

2 Answers 2

4

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.