Solved [WorldGuard] Get ProtectedRegion from string

Discussion in 'Spigot Plugin Development' started by stijnb1234, Aug 2, 2018.

  1. Hello,

    I want to get an ProtectedRegion from an string which contains an Region ID.

    I have this code for now:
    Code (Java):

    public static ProtectedRegion getRegionfromString(String str, Location loc) {
            RegionManager regions = wgp.getRegionManager(loc.getWorld());
            Map<String, ProtectedRegion> mp = regions.getRegions();
            for (Entry<String,ProtectedRegion> pair : mp.entrySet()) {
                if(pair.getValue().getId().equals(str)) {
                    return pair.getValue();
                }
            }
            return null;
        }
     
    But this code isn't working well.
    Do you have an better option to fix this?

    Kind regards,

    Stijn
     
  2. Solved already. It returns null because getID() is in lowercase and str was in uppercase.

    I have this code for now and it works ;)

    Code (Java):
    public static ProtectedRegion getRegionfromString(String str, Location loc) {
            String strgood = str.toLowerCase();
            RegionManager regions = wgp.getRegionManager(loc.getWorld());
            Map<String, ProtectedRegion> mp = regions.getRegions();
            for (Entry<String,ProtectedRegion> pair : mp.entrySet()) {
                if(pair.getKey().equals(strgood)) {
                    return pair.getValue();
                }
            }
            return null;
        }
     
  3. Why iterating over the map when map.get(str) is available. I assume that the key is the region name.
     
    • Like Like x 1
  4. Thanks! ;)

    My new code:

    Code (Java):

    public static ProtectedRegion getRegionfromString(String str, Location loc) {
            String strgood = str.toLowerCase();
            RegionManager regions = wgp.getRegionManager(loc.getWorld());
            Map<String, ProtectedRegion> mp = regions.getRegions();
            ProtectedRegion reg = mp.get(strgood);
            if (reg != null) {
                return reg;
            } else {
                return null;
            }
        }
     
     
  5. You can reduce that to
    Code (Text):
    return reg;
     
    • Like Like x 1