【问题标题】:Java - How can i compare chars with other chars?Java - 我如何将字符与其他字符进行比较?
【发布时间】:2015-11-30 06:16:55
【问题描述】:

我的目标是从用户那里获得特定的输入(仅限 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');
  }

【问题讨论】:

  • 你有一个逻辑缺陷,不要使用 or 条件(它总是符合逻辑的),而是使用 and 语句,推理,如果响应等于 A,B,C or D 然后其他三个条件仍然成立。
  • 我猜你得到的是小写字母'a'、'b'等而不是大写'A'、'B'等?尝试System.out.println(response[i]);进行调试。

标签: java arrays chars


【解决方案1】:

我会这样写

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

【讨论】:

  • 为什么不使用 contains(...) 而不是 indexOf(...)?
  • @L.Butz 你可以写成"ABCD".contains("" + response[i]) 问题是Java 8 中没有String.contains(char)
  • 在“请重试”方法中使用 .println(),并检查“ABCDabcd”或调用 Character.toUpperCase()。另外,只是一个警告;如果 nextLine() 返回的字符串是空字符串,程序就会崩溃!
  • 我认为创建一组允许的字符而不是签入字符串会更干净。 Set allowedCharacters = new HashSet(Arrays.asList('A','B','C','D')) 然后检查这个集合是否包含这个字符。
【解决方案2】:

你的条件是倒退的。当你得到它A你会得到

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

会过去的。

将其更改为:

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

【讨论】:

  • 响应怎么可能是A和B和C和D?
  • 我认为尼古拉斯试图应用摩根斯定律 (en.wikipedia.org/wiki/De_Morgan's_laws) 并同时修复了代码。但是仍然不行,答案应该以不那么混乱和更简单的方式重新编码。尝试和失败可能是理解逻辑的一个很好的教训;)。
  • 我应用德摩根定律 >_or 更改为 and 但不认为这不是所要求的.. 抱歉
猜你喜欢
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 2017-02-20
  • 2010-10-06
  • 1970-01-01
  • 2013-05-06
相关资源
最近更新 更多