0

I'm very new to Java, and I want to make a very simple login Java-program. Don't think about security issues and such in this example, I just need help to get it right. My "Account informations" has to be stored in an Array.

This is my code: -- MAIN --

import java.util.Scanner;
public class BATM {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String username;
    String password;

    System.out.println("Log in:");
    System.out.println("Indtast username: ");
    username = input.nextLine();

    System.out.println("Indtast password: ");
    password = input.nextLine();

    users check = new users(username, password);

    if(check.auth()) 
        System.out.println("You are logged in");



}

}

-- users ---

public class users {
private String username;
private String password;
private String[][] accounts = {{"jesper", "abc123"},{"christian", "abc123"}};

public users(String user, String pass){
    username = user;
    password = pass;
}

public boolean auth(){
    if((username == accounts[0][0]) && (password == accounts[0][1]))
        return true;
    else
        return false;
}

}

I guess this should be a quite simple function, but for some reason the if-statment will never return "true".

What am I doing wrong?

Jesper.

Jesper Bruun Hansen
  • 376
  • 2
  • 5
  • 16

2 Answers2

1

try this..

if((username.equals(accounts[0][0])) && (password.equals(accounts[0][1])))
subash
  • 3,116
  • 3
  • 18
  • 22
0

you are doing the string comparison wrong, in java you need to use .equals() isntead of == the latter compares two object references, this is not what you want.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
  • If I pass in the informations directly, "jesper" and "abc123", the if-statement is true. But for some reasons not when using the variable? – Jesper Bruun Hansen Nov 17 '13 at 18:17
  • yes, this probably because JVM is smart enough to use the same string object for the same string literal. all in all your use of `==` is wrong. – Uku Loskit Nov 17 '13 at 18:22
  • Hey Uku, your advice did the trick, thank you! – Jesper Bruun Hansen Nov 17 '13 at 18:24
  • for future reference: objects in java implement a `equals` method. For java `String` this method is defined to compare the string values character by character. The correct way of comparing objects is using the `equals` method. Java also has primitive types like `ints` and `double`s, these are not `Object`s so you can compare them with `==`. Shortly put: never use "==" for comparing objects (this compares the object references, which are basically memory addresses). – Uku Loskit Nov 17 '13 at 18:27
  • Hi again, Uku. This it great info - I think the explains why the == operator works, in my world, "sometimes and sometimes not". :) – Jesper Bruun Hansen Nov 17 '13 at 18:33