Java - 如何将字符与其他字符进行比较?

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

最佳答案

我会这样写

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

或者

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

关于Java - 如何将字符与其他字符进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32392119/

相关文章:

c - C (Arduino) 中的字符串数组(char 数组)。我如何完成它?

java - JFrame 与 Main 中的其他类组合时无法打开

javascript - 将 2 个 api 响应的结果合并到一个 JavaScript 数组中

arrays - 如何在线性时间内对二进制数组进行排序?

php真正的多字节字符串随机播放功能?

.net - C++ 中的 BSTR 和 SysAllockStringByteLen()

java - Selenium 选择By.Xpath 在一个div 之间

java - 为什么我的 spring 验证注释不起作用

java - 如何使用 maven-jar-plugin 创建带有 .class 文件的测试 jar?

C - 'struct' 元素的动态数组