首页 > 解决方案 > If语句用于处理来自用户的意外响应以猜测数字程序不起作用

问题描述

我目前正在开展一个“猜数字”项目,我的要求之一是处理来自用户的意外输出。我还想知道我应该将这段代码放在代码中的哪个位置,因为我的代码感觉非常杂乱无章。

不是我使用的 if 语句没有编译,我不知道为什么。

while (!text.equals("yes")){
  System.out.println("Is your number " + (guess) + "?");
  System.out.println("yes,higher,or lower");
  text = reader.nextLine();

  if (text.equals("higher")){
    min = guess + 1;
  }

  if (text.equals("lower")){
    max = guess - 1;
  }
  guess = (max + min)/2;

  if (text.equals("yes")){
    System.out.println("Yay! I guessed it.");
  }

  if (!text.equals("yes" || "higher" || "lower" || "ok")){
    System.out.println ("I dont understand " + (text));
    System.out.println("Is your number " + (guess) + "?");
    System.out.println("yes,higher,or lower");
  }
}

期望的输出

Think of a number between 1 and 1000
Type ok when you're ready
 ready
 You said ready
 I guess that means you're ready
 Don't forget your number
Is your number 500?
 yes, higher, or lower
 no
 I don't understand no
 Is your number 500?
 yes, higher, or lower
  lower
 Is your number 250?
 yes, higher, or lower
 yes
Yay! I guessed it
=======
//error with my code
exit status 1
Main.java:38: error: bad operand types for binary operator '||'
      if (!text.equals("yes" || "higher" || "lower" || "ok")){
                         ^
   first type:  String
  second type: String
 1 error

标签: javaif-statementcompiler-errors

解决方案


您可以将您的 if 条件更改为

text.matches("yes|higher|lower|ok")

推荐阅读