0

I am currently working an a "guess a number" project and one of my requirements is to handle unexpected output from the user.I also would want to know where in the code I should put this piece of code because my code feels very disorganized.

Right not I am using an if statement that isn't compiling and i'm not sure why.

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

DESIRED OUTPUT

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
  • 1
    Possible duplicate of [String.equals() with multiple conditions (and one action on result)](https://stackoverflow.com/questions/10208052/string-equals-with-multiple-conditions-and-one-action-on-result) – Ivar Dec 21 '18 at 16:25

3 Answers3

0

The statement should be:

if (!(text.equals("yes") || text.equals("higher") || 
      text.equals("lower") || text.equals("ok"))) {
    ...
}

Anyway I would recommend using a switch instead:

switch(text) {
    case "lower":
        ...
        break;

    ... 

    default:
        System.out.println ("I dont understand " + (text));
        ...
}
luk2302
  • 55,258
  • 23
  • 97
  • 137
0

I think you are looking for :

if (!text.matches("yes|higher|lower|ok")) {

  // ...

}

Here you check if the String text doesn't matches any of the following Strings :

  • yes

  • higher

  • lower

  • ok
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
0

You can change your if condition to and that will do

text.matches("yes|higher|lower|ok")
shelholmes221
  • 518
  • 1
  • 7
  • 18