[英]Java getting string from list with integers and strings
我試圖將一個玩家在我的世界中的位置保存到列表中,但是現在如何通過在playerName上搜索列表來獲取我的位置?
創建列表類的代碼段和列表
public static class Character {
private String name;
private Location location;
public Character(String name, Location location) {
this.name = name;
this.location = location;
}
}
public static class Location {
private int x;
private int y;
private int z;
public Location(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
List<Character> rawInput = new ArrayList<Character>();
我在列表中添加項目的代碼段:
else if (args[0].equalsIgnoreCase("select"))
{
int tmpX = (int)player.getLocation().getX();
int tmpY = (int)player.getLocation().getY();
int tmpZ = (int)player.getLocation().getZ();
rawInput.add(
new Character( player.getName(), new Location( tmpX, tmpY, tmpZ )));
player.sendMessage(
ChatColor.GOLD + "[PlusCommands] " + ChatColor.GREEN
+ "selected location set to player location!");
}
這一切都很好,但我如何獲取數據,例如:
這是一個包含位置的列表:Playername XYZ:
球員三人32 13 46
PlayerTwo 12 60 212
PlayerOne 43 62 523
所以我想在這個例子中搜索合適的玩家我是PlayerOne因此我想從playerList獲取數據,其中字符串顯示為PlayerOne
在這種情況下就是這個:PlayerOne 43 62 523
我該怎么做呢???
如果沒有,我希望我很清楚。
代替List<Character> rawInput = new ArrayList<Character>();
使用Map<String,Character> rawInput = new LinkedHashMap<>();
添加播放器:
rawInput.put( aNewCharacter.getName(), aNewCharacter );
您應該檢查put的返回值:如果非null,則已使用該名稱。 閱讀java.util.Map的Javadoc
要找到一名球員:
Character c = rawInput.get( "PlayerOne" ); // returns PlayerOne 43 62 523
您需要將getter添加到這些類中,如下所示:
package com.sandbox;
public class Sandbox {
public static void main(String[] args) {
Character player = new Character("Foo", new Location(1, 2, 3));
int tmpX = player.getLocation().getX();
int tmpY = player.getLocation().getY();
int tmpZ = player.getLocation().getZ();
}
public static class Character {
private String name;
private Location location;
public Character(String name, Location location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public Location getLocation() {
return location;
}
}
public static class Location {
private int x;
private int y;
private int z;
public Location(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
}
}
記下我的main
。 它表明您不需要轉換為(int)
。
static Map<String,Location> nameAndLocation = new HashMap<String, Location>();
public Character(String name, Location location) {
this.name = name;
this.location = location;
addToMap(this.name, this.location);
}
public static void addToMap(String name, Location location) {
nameAndLocation.put(name,location);
}
public static Location getLocation(String name) {
return nameAndLocation.get(name);
}
這是一些非常混亂的代碼。
您不應該創建自己的Location或Player類,因為Bukkit已經包含其中一個。 而不是制作自己的,使用org.bukkit.util.Location
+ org.bukkit.entity.Player
,你應該沒有問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.