6rchid
6rchid

Reputation: 1292

if-else loop within a do while loop within another do while loop

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

Upvotes: 0

Views: 137

Answers (2)

Andy Thomas
Andy Thomas

Reputation: 86411

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.

Upvotes: 2

kriyeta
kriyeta

Reputation: 705

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: ");
  }

Upvotes: 1

Related Questions