Comparing User input to an Array of Objects

Viewed 33

I am working on a User login service. Below I am pulling data from a text file to create an array of user objects. I then need to compare console input to see if it matches any of the objects in the the Array, specifically username (array position [0]) and password (array position [1]). I am assigning input to String username and String password. How can I then see if those inputs are at array [0] or [1] in any of the user objects.

public static User[] createArray() throws IOException {

    User[] users = new User[4];
    BufferedReader fileReader = null;
    try {
        fileReader = new BufferedReader(new FileReader("data.txt"));
        String line;
        int i = 0;
        while ((line = fileReader.readLine()) != null) {
            users[i] = new User(line.split(","));
            System.out.println(line);
            System.out.println(users[i]);
            i++;
        }

    } finally {
        if (fileReader != null)
            fileReader.close();

    }
    return users;
1 Answers

You could so something like that and not bother with the User class. This presumes that the passed password is compatible with what is read from the file.

This reads in the Data file and splits the line as you indicated. It then filters each array, looking for a user and password match. If found, it returns true via the ifPresent() method. Otherwise, it returns false.

public static boolean validateUser(String user, String passwd) {
    try (Stream<String> input =
            Files.lines(Path.of("Data.txt"))) {
        return input.map(line -> line.split(","))
                .filter(arr -> user.equals(arr[0])
                        && passwd.equals(arr[1]))
                .findFirst().isPresent();
    } catch (IOEException ioe) {
        ioe.printStackTrace();
    }
    return false;
    
}
Related