简体   繁体   中英

Return value of statement in if in a for each loop

I have this method which uses a for each loop with an if statement in it

public static Apartment getApartment(String aNumber)
    
//for loop to iterate through the list of apartments         
{   
for (Apartment x : listOfApartments) 
  { 
  // Variable to hold the value of returned apartment    
  if (x.getApartmentNo().equalsIgnoreCase(aNumber))
  { Apartment chosen = x;
  }
  else 
  {JOptionPane.showMessageDialog(null, "Apartment not found");
  }
 
}  
return chosen;
} 

I am getting an error that Symbol chosen not found. I think I have declared the variable in wrong place. Any help? Note: This is a method that takes a String and returns an Object Apartment.

You have to rewrite your loop: you should not make a decision that the apartment is not found until you finish the loop. You do not need to assign the value to the temporary variable either - once the apartment is found, return it right away.

You can report that the apartment is not found only when you finish the loop.

for (Apartment x : listOfApartments) { 
    // Variable to hold the value of returned apartment    
    if (x.getApartmentNo().equalsIgnoreCase(aNumber)) {
        return x;
    }
}
JOptionPane.showMessageDialog(null, "Apartment not found");
return null;

what if your condition "x.getApartmentNo().equalsIgnoreCase(aNumber)" evaluates to false?
the Apartment data type "chosen" does not get created!
how can you return something that hasn't been instantiated?

This is a scope issue, Chosen is created in side the if statement.

Declare it outside and set it to null, then the function will either return chosen if the condition is true, or null if it isn't.

public static Apartment getApartment(String aNumber)

//for loop to iterate through the list of apartments         
{   
Apartment chosen = null;

for (Apartment x : listOfApartments) 
  { 
  // Variable to hold the value of returned apartment    
  if (x.getApartmentNo().equalsIgnoreCase(aNumber))
  { chosen = x;
  }
  else 
  {JOptionPane.showMessageDialog(null, "Apartment not found");
  }

}  
return chosen;
}

A simple (and correct) way to write the method would be:

public static Apartment getApartment(String aNumber) {
    for (Apartment x : listOfApartments)
      if (x.getApartmentNo().equalsIgnoreCase(aNumber))
        return x;
    JOptionPane.showMessageDialog(null, "Apartment not found");
    return null;
}

It's not necessary to declare a local variable for a value that should be returned immediately. Also, the message dialog should be presented only after the loop ends, because only then we're sure that no apartment had the number being searched.

Regarding the code in the question, you're right: the variable chosen should have been declared before the for loop, so it can be referenced after the loop. The way you declared it, it's visible only inside the if block.

You're correct; you declared chosen in the wrong place. Declare it right before your loop, but assign it (there) to null. That way, it's guaranteed to have a value when you reach the return line.

Alternatively, assuming only one apartment will match (or, you don't care which one), you can simply put return x; in the if...true case. And return null after the loop, assuming the loop completes. Also, because you are looping, every apartment that doesn't match will show the "not found" message; you probably only want to display that after the loop has completed without finding an apartment.

The variable chosen in your code was trapped inside the scope it was created in, so it couldn't be used outside of the {} . Also, the else branch of the if statement was triggering before the rest of the for loop ran.

You don't really need to save the chosen apartment, you can just return it immediately, like this:

public static Apartment getApartment(String aNumber)
{   
    for (Apartment apartment : listOfApartments) 
    {   
        if (apartment.getApartmentNo().equalsIgnoreCase(aNumber))
            return x;
    }  
    JOptionPane.showMessageDialog(null, "Apartment not found");
    return null;
} 

Declare the variable 'chosen' before the for loop like this:

Apartment chosen = new Apartment();

Also you can break out of the for loop when once you find the apartment you are looking for. If the list is big it might save some time.

函数返回的chosen变量在这里超出范围,在循环开始之前的方法开始处声明它。

Accepted answer is correct but I would strongly suggest to avoid multiple return statements. Code with multiple returns statements is harder to manage. Might not seem like a big deal yet, but when code grows this can become a real issue.

public static Apartment getApartment(String aNumber)
{   
    Apartment result = null;
    for (Apartment apartment : listOfApartments) 
    {   
        if (apartment.getApartmentNo().equalsIgnoreCase(aNumber))
        {
             result = apartment;
             break;
        }
    }  
    if (result == null)
    {
        JOptionPane.showMessageDialog(null, "Apartment not found");
    }
    return result;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM