0

I am unable to change this foreach into a for loop. I can't use a foreach while using linked lists so i need to change this into a for loop instead

 private boolean login(String username, String password) {
    MyList<Admin> admins = null;
    XStream xstream = new XStream(new DomDriver());
    try {
        ObjectInputStream is = xstream.createObjectInputStream(new FileReader("Admins.xml"));
        admins = (MyList<Admin>) is.readObject();
        is.close();
    }
    catch(FileNotFoundException e) {
        admins =  new MyList<Admin>();
        txtFeedBackArea.setText("Password File not located");
        return false;

    }
    catch (Exception e) {
        txtFeedBackArea.setText("Error accessing Password File");
        return false;
    }

    for (Admin admin: admins) {
        if(admin.getUsername().equals(username) && 
admin.getPassword().equals(password))
            return true;
    }
    return false;
}*/
Steyrix
  • 2,796
  • 1
  • 9
  • 23
Jhogan
  • 5
  • 2
  • 1
    Hi, welcome to Stack Overflow! What have you tried so far? – grooveplex Dec 09 '19 at 20:29
  • When you say "I _can't_ use a foreach" do you mean you're **not allowed** to use the [enhanced for loop](https://stackoverflow.com/a/11685345/17300) (because this is homework)? – Stephen P Dec 10 '19 at 00:53

1 Answers1

1

What about this?

for (int i = 0; i < admins.size(); i++) {
    final Admin a = admins.get(i);
    if(a.getUsername().equals(username) && a.getPassword().equals(password))
        return true;
}

By the way, it is always better to use for-each style loop, since it provides more readability and convenience

EDIT: Since you mentioned linked list, it is better to use linked list iterator to iterate over your collection.

for (ListIterator<Admin> iter = admins.listIterator(0); iter.hasNext()) {
    final Admin a = iter.next();
    if(a.getUsername().equals(username) && a.getPassword().equals(password))
        return true;
}

You can also use while loop for that

while (iter.hasNext()) {
// do the work
}
Steyrix
  • 2,796
  • 1
  • 9
  • 23
  • mate this worked thank you so much, what does the final do tho? – Jhogan Dec 09 '19 at 20:52
  • @Jhogan I am glad it helped you. The `final` keyword marks a variable as constant, in this case it means that you can't reinitialize a with another instance of class Admin (in other words, change the object it references). However you can still edit its members. For primitive types (`int,float,char` and etc.) `final` simply means that the value of variable cannot be modified – Steyrix Dec 09 '19 at 20:56
  • Since the question mentions “linked lists”, it’s preferable to use an `Iterator` based loop rather than index based… – Holger Dec 10 '19 at 10:20
  • @Holger thank you, you are right. I edited my answer for clearance – Steyrix Dec 10 '19 at 10:35