0

I'm still newbie to java programming. And can anybody tell me what's wrong with the source code? When I run the code, the conditional assignment always outputs "login failed".

import java.util.Scanner;
public class ProgramBiodataMahasiswa {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String username, password, output;
        System.out.print("Enter username     : ");
        username = input.nextLine();
        System.out.print("Enter password     : ");
        password = input.nextLine();
        output = (username=="kesit" && password=="ps123") ? "login successfully" : "login failed" ;
        System.out.println(output);
    }
}
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
yomatok
  • 11
  • 2
  • try using output = (username.equals("kesit") && password.equals("ps123")) ? "login successfully" : "login failed" ; – WannaBeGeek Oct 15 '15 at 05:58
  • 1
    You should also check out [this question](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) to see why you should use `equals` instead of `==`. – Saad Oct 15 '15 at 06:00

3 Answers3

2

Use .equals

output = (username.equals("kesit") && password.equals("ps123")) ? "login successfully" : "login failed" ;
Harshit
  • 5,147
  • 9
  • 46
  • 93
1

With Strings ("quest" and "ps123") you shouldn't be using == to check if they equal. This will compare the pointer and due to the fact that String in Java are immutable, the pointers will always be different. Therefore use

username.equals("kesit") && password.equals("ps123").

That should work!

1

You can't compare strings in Java using ==. You should use equals method. e.g. username.equals("kesit") && password.equals("ps123")

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115