mercredi 27 décembre 2017

Java If statement not returning expected result [duplicate]

This question already has an answer here:

I'm trying to get my hands dirty with JAVA, I'm currently using Eclipse as my compiler and when I'm trying to execute this code

    import java.util.*;
    public class HelloWorld {

    public static void main(String[] args) 
    {
        String password = null;
        Scanner in = new Scanner(System.in);
        System.out.println("Please Enter Your Name: ");
        String UserName = (String)(in.nextLine());
        if(UserName == "Michael")
        {
            System.out.println("Hello " + UserName);
        }
        else
        {
            System.out.println("Invalid User");
        }

    }

}

Everytime I run it, even with the correct name it says "Invalid User", the only way I've been able to get it to work is to hard set the if statement to Michael == "Michael", which for obvious reasons is not something I'd prefer to do.

I know Java.util.* is not exactly the most low-cost memory method but found it's minimal compared to simplicity sake.

Aucun commentaire:

Enregistrer un commentaire