Java - 我怎样才能将chars与其他字符进行比较?

时间:2015-09-04 07:09:58

标签: java arrays chars

我的目标是获取用户的特定输入(仅限A,B,C和D)。

例如:如果我输入字母A,if语句将执行(它不应该)。与do while相同。 (逻辑错误)

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

2 个答案:

答案 0 :(得分:6)

这就是我写它的方式

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

你做错了是你需要写

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

答案 1 :(得分:0)

你的情况是倒退的。当你得到它A你将得到

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

将通过。

将其更改为:

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