-1

New to programming, please forgive if this is stupid

I'm trying to loop through two arrayLists at once in Java. Below is my code and beneath that is the code I am trying to implement (if this is possible).

In a class "Tournament", it creates and stores Champion objects. I have two arrayLists: championList(this stores all hard coded champion objects into the game) and teamList(champion objects are added to a players team).

I want to check if the champion object in question (the parameter in the method) exists by looping through both arrayLists and returning a specified int if it doesn't.

Working code:

    public int retireChamp(String nme){
    for(Champion temp: championList)
    {
       if(temp.getName().equals(nme)) 
       do something etc...
    }

Code I want to implement if possible

    public int retireChamp(nme){
    for(Champion temp: championList && teamList)
    {
       do something...
    }
  • That cant be done with a enhanced for loop. Use a plain old for loop with an index. – f1sh Dec 29 '22 at 10:45
  • @f1sh thank you for your reply. The problem with using an old loop is that the parameter nme is a String (realising now I didn't include this, apologies), and Champion objects don't have any int attributes to match with the index of the old for loop. Any ideas how to combat this? – aidan gaskin Dec 29 '22 at 10:51
  • The code has syntax errors. Please [edit] the post and fix the errors. --- "*`temp.getName() == nme`*" - Please read: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) (this holds true for any reference-type in Java, not only `String`s) – Turing85 Dec 29 '22 at 10:52
  • you can't iterate over both the list neither by enhanced loop nor by ola plain loop because both list can have different numbers of element. Use 2 nested loops – Saima Haji Dec 29 '22 at 11:05

1 Answers1

0

If I understand correctly, your lists do not always seem to contain the same elements, and if they do, not necessarily in the same order. What you actually want to do is not iterate over the two lists at the same time but check if there is an element in both lists that has the same attribute as the passed parameter. You can do this one after the other:

public int retireChamp(nme){

    boolean inChampList = false;
    boolean inTeamList  = false;

    for(Champion temp: championList) {
       if(temp.getName().equals(nme)){
          inChampList = true;
          break;
       }
    }

    for(Champion temp: teamList) {
       if(temp.getName().equals(nme)){
          inTeamList = true;
          break;
       }
    }

    if(inChampList && inTeamList) {
       //your logic here - nme is in both lists
    } else if (inChampList ^ inTeamList) {
       //your logic here - nme is in one of the lists
    } else {
       //your logic here - nme is in none of the lists
    }
}
Queeg
  • 7,748
  • 1
  • 16
  • 42
Eritrean
  • 15,851
  • 3
  • 22
  • 28