Search code examples
javaarrayschars

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

Solution

  • 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')