0

I'm trying to make a game and I am sorting out the account's and im doing it in text files at the moment as im just playing around, the text file for example is,

username
password

and when I run the code below , it runs the else statement every time when the details I enter are correct.

String player;

Scanner loadPlayer = new Scanner(System.in);
System.out.print("Enter Username: ");
String username = loadPlayer.nextLine();
System.out.println();
System.out.print("Enter Passwork: ");
String password = loadPlayer.nextLine();
System.out.println();

try {
        File file = new File("/home/kieran/Desktop/project/accounts/"+username+".txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
        }
        fileReader.close();
        String userData[] = stringBuffer.toString().split("\n");
        System.out.println(userData[0]);
        System.out.println(userData[1]);
        if (userData[0] == username && userData[1] == password){
                player = username;
                System.out.println(player);
        }
        else{
                System.out.println("Username, "+username+" does not exist, please try again!");
                loadPlayer();
        }
} catch (IOException e) {
        e.printStackTrace();
}
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Kieran Lavelle
  • 446
  • 1
  • 6
  • 22
  • 4
    possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – BackSlash Dec 05 '14 at 13:44

3 Answers3

2
if (userData[0].equals(username) && userData[1].equals(password)){
   player = username;
   System.out.println(player);
}
Tkachuk_Evgen
  • 1,334
  • 11
  • 17
1

Your string comparison implementation is not OK. Replace this line

if (userData[0] == username && userData[1] == password){

with this one:

        if (userData[0].trim().equals(username.trim()) && userData[1].trim().equals(password.trim())){
JuanZe
  • 8,007
  • 44
  • 58
0

try this

    if (userData[0].equals(username) && userData[1].equals(password)){
            player = username;
            System.out.println(player);
    }
    else{
            System.out.println("Username, "+username+" does not exist, please try again!");
            loadPlayer();
    }