0

When 'y' or 'Y' is inputted, I want the code to the prompt System.out.print("Y/y or N/n: "); starting from the first do,but instead the code will prompt System.out.print("bad answer, try again: ");, and I only want char besides y,Y,n,N to be the case.

The only code that follows is when 'n' or 'N' is entered, following System.exit(0);

import java.util.Scanner;
public class Test
{
   public static void main(String[] args)
   {
      Scanner kb = new Scanner(System.in);
      char ch;
      do
      {
         System.out.print("Y/y or N/n: ");
         do
         {
            ch = kb.nextLine().charAt(0);
            if (ch == 'n' || ch == 'N')
            {
               System.exit(0);
            }
            else if (ch != 'y' || ch != 'Y' || ch != 'n' || ch != 'N');
            {
               System.out.print("bad answer, try again: ");
            }

         }
         while (ch != 'y' || ch != 'Y' || ch != 'n' || ch != 'N');
      }   
      while (ch == 'y' || ch == 'Y');
   }
}
1
  • 1
    You should use && instead of ||. Commented Nov 17, 2014 at 17:41

2 Answers 2

2

Because you're using OR rather than AND, this condition will always be true:

else if (ch != 'y' || ch != 'Y' || ch != 'n' || ch != 'N')
{
    System.out.print("bad answer, try again: ");
}

By the way, you could simplify this to have a single do-while. If the answer is bad, just go on to the next iteration of the outer loop.

Sign up to request clarification or add additional context in comments.

Comments

1

Remove semicolon and check for ch and take AND. Code could be like this:

else if (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N')
{
       System.out.print("bad answer, try again: ");
}

OR

Remove semicolon and check for ch and take OR and finally take NOT. Code could be like this:

 else if (!(ch == 'y' || ch == 'Y' || ch == 'n' || ch == 'N'))
 {
       System.out.print("bad answer, try again: ");
  }

3 Comments

+1 - I missed that semicolon! Might be worthwhile to explain to the OP what that semicolon causes to happen.
@AndyThomas the statement after 'if' runs no matter if the expression is true or not. because ; acts as a null statement after 'if' Thats why 'if' statement completes after ; and statements next to ; doesn't depend on if conditon.
In addition, the { System.out.println(...) } is legal because Java allows a sequence of statements and declarations to be enclosed in braces, as a block. (BTW, the semicolon is technically an "empty statement.")

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.