Cito
Cito

Reputation: 23

Java - How can i compare chars with other chars?

My goal is to get specific inputs from the user (A, B, C, and D only).

for example: If i enter the letter A, the if statement will execute (its not supposed to). and the same with the do while. (Logic Error)

  char[] response = new char[20];
  Scanner k = new Scanner(System.in);

  //Prompts User to fill array with their responses
  for(int i=0; i<response.length; i++) {
       //Input validation
       do {
          System.out.println("Answer "+(i+1)+":");
          response[i] = k.nextLine().charAt(0); 

          if(response[i] != 'A' ||response[i] != 'B' || response[i] != 'C' ||response[i] != 'D')
              System.out.print("Try Again. ");
       }
       while(response[i]!= 'A' ||response[i] != 'B' ||response[i] != 'C' ||response[i] != 'D');
  }

Upvotes: 2

Views: 110

Answers (2)

Nicholas Robinson
Nicholas Robinson

Reputation: 1429

You condition is backwards. When you get it A you will get

if (false || true || true || true) 

which will pass.

Change this to:

if(response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533820

This is how I would write it

Scanner in = new Scanner(System.in);
char[] response = new char[20];

//Prompts User to fill array with their responses
for(int i = 0; i < response.length; i++) {
   for (;;) {
       System.out.println("Answer " + (i + 1) + ":");
       response[i] = in.nextLine().charAt(0);
       //Input validation
       if ("ABCD".indexOf(response[i]) >= 0)
           break;
       System.out.print("Please try again, it must be A, B, C or D");
   }
}

What you were doing wrong is you needed to write

if (!(response[i] == 'A' || response[i] == 'B' || response[i] == 'C' || response[i] != 'D'))

OR

if (response[i] != 'A' && response[i] != 'B' && response[i] != 'C' && response[i] != 'D')

Upvotes: 7

Related Questions