Looping through a List and returning a value

Discussion in 'Plugin Development' started by Etched, Jun 20, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Etched

    Hi all,
    Basically I want to loop through all available teams(a custom class I made) and then if the player is in it, return that team. However, I have no idea what to put for the else statement, as it is required for a vaule to be returned in an if statement. This is the code:
    Code:java
    1. package me.Etched.MCTF2.Managers;
    2.  
    3. import me.Etched.MCTF2.Main;
    4. import me.Etched.MCTF2.API.MCTF2API;
    5. import me.Etched.MCTF2.API.Team;
    6.  
    7. import org.bukkit.entity.Player;
    8.  
    9. public class PlayerManager {
    10.  
    11. private static MCTF2API tfAPI = new MCTF2API();
    12. private static Main tf = tfAPI.getMCTF2();
    13.  
    14. public Team getPlayerTeam(Player p){
    15. for(Team t : tf.teams){
    16. if(t.contains(p)){
    17. return t;
    18. }else{
    19. //Help here pls
    20. }
    21. }
    22. }
    23.  
    24. }
    25.  

    Thanks,
    Etched
     
  2. Offline

    minoneer


    It depends on what you want the return value to be if the player is in none of the teams. Usually, a good approach is to return "null". That indicates to the method calling your method, that he is without a team.
     
  3. Offline

    Etched

    OK, thanks. I was wondering that. But will that stop the rest of the for loop?

    Actually, I can't return null because it needs to return a team.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 9, 2016
  4. Offline

    Necrodoom

    Etched get rid of the else, go to outside of the loop.
    Also, I don't see the problem with returning null. What do you except a team-less player to return?
     
  5. Offline

    Rocoty

    Etched null is of no type but can be assigned to any type. The compiler has no problem with it. I would advise not to have an else statement here, and instead return null at the very end of the method, outside the for-loop. If you really do not want to return null you could throw an exception.

    EDIT: Ninja'd
     
  6. Offline

    Etched

Thread Status:
Not open for further replies.

Share This Page