views:

35

answers:

1

Hey,

I tried to implement a simple yes/no input with java.util.Scanner. My code looks like this:

public boolean ask(String quest){
  String answ = scann(quest + " (y/n)");
  answ = answ.split("")[1].toLowerCase();
  if(answ == "y") { return true; }
  if(answ == "n") { return false;}

  //if answer isnt understood
  printOut("Please enter 'y' or 'n'! Answered: " + answ +"!");
  return ask(quest);
}

To make it short: It ends up with an infinite request for the answer. The answer is never understood, I got no clue what I did wrong.

+3  A: 

You cannot use == to compare strings in Java (well, you can, but it's not the right way to compare their literal values). You need to use equals():

  if ("y".equals(answ)) { return true; }
  if ("n".equals(answ)) { return false; }
BoltClock
Jup. Use "y".equals(answ) if you want to avoid probably possible null pointer exceptions.
InsertNickHere
@InsertNickHere: good catch! Edited.
BoltClock
Perfect. Thank you!
FB55