【问题标题】:Check keyboard input if empty OR not "Y" OR not "X"检查键盘输入是否为空或不是“Y”或不是“X”
【发布时间】:2018-10-26 07:32:33
【问题描述】:

我想检查我的输入是否为空或不是“Y”或不是“X”

while (weiterInput.isEmpty() || !weiterInput.equals("X") || !weiterInput.equals("Y")) {..}

如果我输入“X”或“Y”,它不会像预期的那样退出循环。

【问题讨论】:

  • &&,而不是||。你有错误的运营商。还有!isEmpty
  • 如果输入 X 或 Y,其他否定条件仍然为真

标签: java input while-loop


【解决方案1】:

我想你只需要这个:

while (!weiterInput.matches("[XY]?")){...}

编辑:

我还可以用更少的编码测试小写字母和其他变体(是、是、是、y、Y)

在这种情况下,只需将正则表达式更改为:

if (!weiterInput.matches("(?i)(yes|y)?")){

注意(?i)会匹配大小写不敏感,所以不用担心YES,Yes,Y..

【讨论】:

  • 很好,因为它是一个是或不是的问题,我也可以用更少的编码测试小写和其他变体(是、是、是、y、Y)
  • @SteffenBauer 在这种情况下你可以使用if (!weiterInput.matches("(?i)(yes|y)?")){
【解决方案2】:

你的逻辑搞错了。

如果你想检查它是否为空或等于X或等于Y,它会是

(weiterInput.isEmpty() || weiterInput.equals("X") || weiterInput.equals("Y"))

如果你想要 相反的,只需否定整个表达式

(!(weiterInput.isEmpty() || weiterInput.equals("X") || weiterInput.equals("Y")))

【讨论】:

    【解决方案3】:

    此循环永远不会终止,因为weiterInput 永远不会等于“X”和“Y”,因此!weiterInput.equals("X")!weiterInput.equals("Y") 将始终为true

    你需要:

    while (weiterInput.isEmpty() ||
          (!weiterInput.equals("X") && !weiterInput.equals("Y"))) {            
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2018-05-26
      • 2011-11-04
      相关资源
      最近更新 更多