Can anyone help me with this loop?

Discussion in 'Plugin Development' started by HeadGam3z, Jul 22, 2014.

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

    HeadGam3z

    I'm doing a check to see if a player (a[1]) is online, and if so, do something. But the problem is, if at any time a[1] is not a match with any of the online players (the first player), it will just break the loop. Which is semi what I want to do... But I want to loop through all of the players, check if there is a match, and if not, then break the loop - not just break the loop when there isn't a match on the first/second/third try (depending on how many players ofc)

    First off, I know I'm doing this wrong, obviously. So if someone could point me in the right direction that'd be great, thanks!

    Loop
    Code:java
    1. for (Player onlineP : Bukkit.getServer().getOnlinePlayers()) {
    2. if (onlineP.getName().equalsIgnoreCase(a[1])) {
    3. @SuppressWarnings("deprecation")
    4. Player onPlayer = (Player) Bukkit.getServer().getPlayer(a[1]);
    5. u.setHappyLevel(a[0], onPlayer);
    6. return true;
    7. } else {
    8. p.sendMessage(u.getPrefix() + ChatColor.DARK_RED + "Error: " + a[1] + " isn't online.");
    9. break;
    10. }
    11. }

    :)
     
  2. Offline

    Zettelkasten

    HeadGam3z You are using the wrong argument in Line 5 of the snippet.

    Also, I would reconsider just using the methods from Bukkit to get a player by name:
    Code:java
    1. Bukkit.getPlayer(a[1]); // will also work if not the full name is supplied; Zet will also return Zettelkasten
    2. Bukkit.getPlayerExact(a[1]);

    To check if the player is online, check if the method returned null:
    Code:java
    1. Player onPlayer = Bukkit.getPlayer(a[1]);
    2. if (onPlayer == null) { // Error }
    3. else { // Do stuff with the player }
     
  3. Offline

    LordVakar

    Zettelkasten
    Actually I don't think he's using the wrong argument on line 5.
     
  4. Offline

    thecrystalflame

    i dont understand why you would save Bukkit.getPlayer(a[1]) to a variable. when you already know that onlineP is the exact object your trying to save. seriously its like doing this:

    Code:java
    1.  
    2. Player player = Bukkit.getPlayer("TheCrystalFlame"); //its already saved here!
    3. if (player.getName().equals("TheCrystalFlame")) {
    4. Player player2 = Bukkit.getPlayer("TheCrystalFlame"); //WHY WOULD YOU DO THIS>!!!
    5. }
    6.  


    seriously just do

    u.setHappyLevel(a[0], onlineP);
     
    Gnat008 likes this.
  5. Offline

    1Rogue

    Your logic is a bit flawed, you need to get the relevant player object first, not do all your implementation in the loop. Bukkit#getPlayer will do that for you, and if they aren't online it will return null (which means you can work with that).
     
Thread Status:
Not open for further replies.

Share This Page