Jump to content

Weird behavior for player.getName()


Delision

Recommended Posts

I've run across some weird behavior with the String returned by player.getName() and I think I see what's going on but I'm hoping someone can shed some light on it and show me a better solution to the problem than the one I have come up with. I have a function which will detect if there are nearby players with any name but the accepted ones (here I just use a single name as an example). However, what I have found is that even when it reaches the player of the allowed name, the .equals() comparison will return false no matter what. I've printed out the string generated by player.getName() and my predetermined allowed player name and they are identical in the logger -- with no extra spaces on the beginning or the end, but there still seems to be some sort of invisible escape characters which are returned by player.getName() which causes the comparison to fail.

Here is my code:

  
private boolean detectedPlayers() {
  List<Player> nearbyPlayers = players.getAll();
  nearbyPlayers.remove(myPlayer());
  String allowedPlayer = "27 dragonman 178";
  
  for(Player a : nearbyPlayers) {
      String playername = a.getName();
      if(!playername.equals(allowedPlayer)) {
        log("Non-whitelisted character detected!");
        return true;
      }
  }
  return false;
}

 

My solution (ugly as it is) does work, but it's not really that pretty. Basically I delete all invisible characters returned by player.getName() and then run the comparison again, and it works. The modification is the addition of

replaceAll("\\P{Print}","")

I have to call this on my original String as well because this replaceAll() also deletes any spaces in the name.

  
private boolean detectedPlayers() {
  List<Player> nearbyPlayers = players.getAll();
  nearbyPlayers.remove(myPlayer());
  String allowedPlayer = "27 dragonman 178".replaceAll("\\P{Print}","");
  
  for(Player a : nearbyPlayers) {
      String playername = a.getName().replaceAll("\\P{Print}","");
      if(!playername.equals(allowedPlayer)) {
        log("Non-whitelisted character detected!");
        return true;
      }
  }
  return false;
}

 

Is there a better way to run comparisons on Strings returned by player.getName() to avoid this?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...