0

I'm having an issue updating an object inside a method

public Admin getAdminByName(String name) throws InexistentUserException {

        Admin currentAdmin = null;
        for (Admin admin : adminList){
            if (admin.getUserName().equals(name)){
                currentAdmin = admin; //This update is still null
            }
            else { throw new InexistentUserException("The admin does not exist");}
        }
        return currentAdmin;
    }

This code returns null always. I don't need to create a new object Admin, as I should create more than the already existing ones, I just need to locate one by its name

2
  • This method can only return null if adminList is empty. Commented Nov 12, 2020 at 23:11
  • Why not just return admin; instead of setting the currentAdmin variable? Commented Nov 12, 2020 at 23:12

4 Answers 4

1

You are throwing in the wrong place. Right now your code iterates over the list and as soon as it doesn't find a match, it throws the exception.

Ideally what you want to do is search until you find a match and then stop and return that match.

After the for loop, you'd want an if statement that checks whether your currentAdmin is null. If it is then you'd throw a NoAdminExceptionFound or something along those lines.

package eu.webfarmr;

public class Admin {
    private String username;
    private final static Admin[] adminList = new Admin[] {new Admin("Alice"), new Admin("Bob"), new Admin("Carol") };
    
    public static Admin getAdminByName(String name) throws InexistentUserException {

        Admin currentAdmin = null;
        for (Admin admin : adminList){
            if (admin.getUserName().equals(name)){
                currentAdmin = admin; //This update is still null
            }
        }
        if (currentAdmin == null) {
            throw new InexistentUserException("The admin does not exist");
        }
        return currentAdmin;
    }
    
    public Admin(String username) {
        this.username = username;
    }
    
    public String getUserName() {
        return this.username;
    }
}

Edit - a version with while to be more efficient

package eu.webfarmr;

import java.util.Arrays;
import java.util.Iterator;

public class Admin {
    private String username;
    private final static Admin[] adminList = new Admin[] {new Admin("Alice"), new Admin("Bob"), new Admin("Carol") };
    
    public static Admin getAdminByName(String name) throws InexistentUserException {

        Admin currentAdmin = null;
        boolean found = false;
        Iterator<Admin> iterator = Arrays.asList(adminList).iterator();
        while(!found && iterator.hasNext()) {
            Admin admin = iterator.next();
            found = admin.getUserName().equals(name);
            if (found){
                currentAdmin = admin;
            }
        }
        if (!found) {
            throw new InexistentUserException("The admin does not exist");
        }
        return currentAdmin;
    }
    
    public Admin(String username) {
        this.username = username;
    }
    
    public String getUserName() {
        return this.username;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Solved, thanks for the help. Exception taken out of the loop, removed the local variable currentAdmin and returned the admin in the loop.
Unless OP is specifically looking for the last match, the simplest implementation would be for (Admin admin : adminList) if (admin.getUserName().equals(name)) return admin; throw new InexistentUserException();
true but I hate breaking out of a for loop with a return statement but that is indeed the shortest path
1

if you are using java 8 or above, you might consider using java streams to solve this. https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

Streams will let you iterate through elements and filter based on an objects field, which in this case would be the Admins name. Note that it assumes that each admin has a unique name.

An example related to your problem:

(If adminList is a java.util.List) ''' public static Admin getAdminByName(String name) throws Exception {

    return adminList.stream()
    .filter(admin -> admin.getUserName().equals(name))
    .findFirst()
    .orElseThrow(() -> new Exception("Admin  " + name + " does not exist"));
}

'''

If the adminList is an array, try:

''' public static Admin getAdminByName(String name) throws Exception {

    return Arrays.stream(adminList)
    .filter(admin -> admin.getUserName().equals(name))
    .findFirst()
    .orElseThrow(() -> new Exception("Admin " + name +" does not exist"));
}

'''

Comments

0

at the first iteration of for loop if the condition becomes false then exception will be thrown and null will return. You need to change your throwing section of your code and put it at the end of for loop and check if it didn't find and its null then throw the exception:

public Admin getAdminByName(String name) throws InexistentUserException {
    Admin currentAdmin = null;
    for (Admin admin : adminList) {
        if (admin.getUserName().equals(name)) {
            currentAdmin = admin; // This update is still null
            break;
        }
    }
    if(currentAdmin == null) {
        throw new InexistentUserException("The admin does not exist");
    }
    return currentAdmin;
}

Comments

0

You can solve it like that

public Admin getAdminByName(String name) throws InexistentUserException {

    boolean found = false;

    Admin currentAdmin = null;
    for (Admin admin : adminList) {
        if (admin.getUserName().equals(name)) {
            currentAdmin = admin;
            found = true; // This update is still null
        }

    }
    if (found) {
        return currentAdmin;
    } else {
        throw new InexistentUserException("The admin does not exist");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.