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;
}
}
adminListis empty.return admin;instead of setting thecurrentAdminvariable?