0

Here's the code:

import java.util.Scanner;

public class Hallo {

public static void main(String[] args) {

    System.out.println("What is your name?");

    Scanner firstScanner = new Scanner(System.in);

    String imput = firstScanner.nextLine();

    if (imput.length() > 6 ) {

        System.out.println("That's quite a long name!");

    }

    else {

        System.out.println("A nice and consise name you have.");
    }

    imput = firstScanner.nextLine();

    if (imput == "Thank you") {

        System.out.println("Yes, so how many siblings do you have?");

    }

    else {

        System.out.print("Aren't you suppose to say 'Thank you' when someone complements you?");

    }


}

}

When I type, "Thank you" in the console, it still says "Aren't you suppose to say 'Thank you' when someone complements you?" even though I typed it exactly as I declared it. Why won't it ask me how many siblings I have?

Sorry if that was hard to understand.

2 Answers2

0

Use the string equals() method to check for equality in the if statement. right now it's returning false because it's only checking the memory locations and not the value of the string. Also try using equalsignorecase method to make it more robust.

0

That is because the == operator in Java compares whether two values are the same. For primitives such as int this works fine. But objects, and Strings are objects, it compares whether two objects are the same, not whether their content is equal.

There might exist two different String objects representing exactly the same text, but being two different objects.

So always use

string1.equals(string2)

or

string1.equalsIgnoreCase(string2)

for string comparison.

MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44