Solved Looping through players

Discussion in 'Spigot Plugin Development' started by _diam, Apr 28, 2017.

  1. Hey there! So, I really can't figure out why this is happening for me, because it's always worked in the past (I haven't changed my code or Spigot version). I'm trying to loop through all online players and only kick the players who don't have a permission node. There are no errors in console, in my IDE, and (as far as I can tell) my code. There are roughly 10 players who should be getting kicked, but it just kicks two or three players and then ignores the rest.

    My code:
    Code (Text):
         public static void kickAllWithoutPerm(Player player, String message) {
            for(Player all : Bukkit.getServer().getOnlinePlayers()) {
                if(!all.hasPermission("plugin.nokick")) {
                    all.kickPlayer("kicked by " + player.getName() + " for " + message);
                    return;
                }
                return;
            }
            return;
        }
    Any ideas as to why it doesn't work? No errors at all, just doesn't kick everyone it should.
     
  2. you're stopping the for-each statement with the return statement. it'll basically run once, and stop dead in its tracks. generally, return statements are used when a value that is processed, is not needed for anything or can be ignored. ex:

    Code (Java):

    if (player.getInventory().getItemInMainHand() == null) {
         return;
    }
    //here, player's hand is not null(empty)
     
    you could also use java 8's stream API, to accomplish what you want.

    Code (Java):

    Bukkit.getOnlinePlayers().stream().filter(player -> !player.hasPermission("permission")).forEach(player -> player.kickPlayer("reason"));
     
    • Agree Agree x 1
    • Winner Winner x 1
  3. Code (Text):
    private void killAllWithoutPerm() {
            for(Player p : Bukkit.getOnlinePlayers())
                if(!p.hasPermission("plugin.nokick"))
                    p.kickPlayer("");
        }
     
  4. Uhh okay?

    Thank you so much, that totally flew by me. Issue was resolved, I removed the return statement (seeing as it was unnecessary). <3