Kieran Lavelle
Kieran Lavelle

Reputation: 446

Not reading from the file correctly in Java

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();
}

Upvotes: 0

Views: 94

Answers (3)

JuanZe
JuanZe

Reputation: 8157

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())){

Upvotes: 1

Black Lion
Black Lion

Reputation: 9

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();
    }

Upvotes: 0

Tkachuk_Evgen
Tkachuk_Evgen

Reputation: 1354

if (userData[0].equals(username) && userData[1].equals(password)){
   player = username;
   System.out.println(player);
}

Upvotes: 2

Related Questions