-2

Well, I really tried to solve (and google) it, but I couldn't.

And sorry for my english and for that idiotic title (This one is the best that came to mind) :)

System.out.println("AM I A GENIUS?");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
 if (s == "yes"){
        System.out.println("^_^");
}
 else{
    System.out.println("I am not a genius(");
}

console: AM I A GENIUS?

yes

I am not a genius(

3 Answers3

0

if (s == "yes") --->> NEVER

instead use

if (s.equals("yes"))

EDIT: just for explain: the first statement is a boolean operator that controls if the references of the object s and the object "yes" are the same.

the second one compares the real content of the String variable.

So, in general, you should never use boolean comparison when using not primitive types.

Lorenzo Barbagli
  • 1,241
  • 2
  • 16
  • 34
0

In fact, you are comparing references and not the 2 String objects.

What you should do is the following:

System.out.println("AM I A GENIUS?");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
 if (s.equals("yes")){
        System.out.println("^_^");
}
 else{
    System.out.println("I am not a genius(");
}

The equals method of the class String now compares the Strings s and "yes" characterwise.

hamon
  • 1,006
  • 6
  • 7
0

I think Roman was right, you should be using .equalsnot ==, they imply different things.

== checks the references to the objects, which can work depending on what what you're comparing, but it's best to use .equals() which compares the content of the strings.

Your code should look like this:

String s = scan.nextLine();
if (s.quals("yes")){
    System.out.println("^_^");
}
 else{
    System.out.println("I am not a genius(");
}

I'd also recommend using a .toLowerCase() on the user input, because that also cause the conditional to return false when the user types "Yes" as supposed to "yes". That would look like: s=s.toLowerCase();

Hope this helps.

Wold
  • 952
  • 1
  • 13
  • 25