0

So I have a very very basic login program that just prints a line when you enter the correct credentials. All it does even if I enter the correct credentials is print the error message out of my if else statement. Any help would be greatly appreciated.

import java.util.Scanner;

public class Exercise4
{
private static String Username = "javacave";
private static String Password = "welcome1";

public static void main(String[] args)
{
    System.out.println("Please enter username");
    Scanner in = new Scanner(System.in);
    String UN = in.nextLine();

    System.out.println("Please enter password");
    Scanner inn = new Scanner(System.in);
    String PW = inn.nextLine();

    if (UN == Username && PW == Password)
    {
        System.out.println("User has logged in successfully!");
    }
    else {
        System.out.println("You have entered the wrong credentials, please try again.");
    }
}
 }

2 Answers 2

2
(UN == Username && PW == Password)

should be:

(UN.equals(Username) && PW.equals(Password))

Whenever you compare between two Strings, use equals() to check the equality of the values, rather than using == which checks if the two references are the same in the memory.

And please, read Code Conventions for the Java Programming Language.

Sign up to request clarification or add additional context in comments.

4 Comments

And this should be a core feature you're learning in your java class. Make sure to read up on the string library. Good luck with your projects. ;)
Thank you very much I just figured it out right before you posted.
Just a note, "Whenever you compare between two Strings" should really be "Whenever you compare between two Objects". this applies to everything that isn't a primitive type. == compares the reference, .equals() can be overloaded and can compare the value.
@AngeloGenovese I agreed, but I was talking specifically about string objects.
0
Scanner scan = new Scanner(System.in);

String userName = scan.nextLine();
String pass = scan.nextLine();

if(userName.equals("123") && pass.equals("123"))
{
    System.out.println("Logged!");
}

else 

{
System.out.println("Error!");
}

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.