Problem with java.util.Scanner & strings
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 underst开发者_Python百科ood
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.
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; }
精彩评论