【发布时间】:2021-10-07 10:18:27
【问题描述】:
我目前正在开发一个我的世界插件,其中包含许多带有许多占位符的项目。
我有一个有两个参数的方法: 一个 ItemStack 和一个字符串数组。
在数组中,奇数位置是变量,偶数位置是它们必须替换的值。
我想知道替换这些变量最有效的方法是什么。
我的代码:
public static ItemStack replace(ItemStack item, String... placeholders) {
ItemMeta meta = item.getItemMeta();
List<String> lore1 = meta.getLore();
String lore = serializeLore(lore1);
String name = meta.getDisplayName();
for(int i = 0; i < placeholders.length; i+=2) {
lore = lore.replace((String)placeholders[i], (String)placeholders[i + 1]);
name = name.replace((String)placeholders[i], (String)placeholders[i + 1]);
}
meta.setLore(Arrays.asList(lore.split("\n")));
meta.setDisplayName(name);
item.setItemMeta(meta);
return item;
}
private static String serializeLore(List<String> lore) {
String result = "";
for(int i = 0; i < lore.size(); i++) {
result += lore.get(i) + (i + 1 < lore.size() ? "\n" : "");
}
return result;
}
例如:
replace(item, "%player%", "John", "%coins%", "2000", "%score%", "80");
编辑: 物品知识示例:
"&7欢迎回来 &a%player%!"
""
“&7与朋友一起玩的疯狂有趣的小游戏:”
"&f - %minigame1%"
"&f - %minigame2%"
"&f - %minigame3%"
"&f - %minigame4%"
"&f - %minigame5%"
"&f - %minigame6%"
"&f - %minigame7%"
"&f - %minigame8%"
""
"&7Coins: &6%coins%"
"&7Score: &2%score%"
"&7Games Played: &9%gamesPlayed%"
""
"&a点击播放!"
"&7%currentPlaying% 正在播放!"
【问题讨论】:
-
您能否举例说明在进行替换之前的知识和名称数据是什么样的?
-
"&7Welcome Back &a%player%!" ""\n "&7Crazy fun minigames to play with friends:" "&f - %minigame1%" "&f - %minigame2%" "&f - %minigame3%" "&f - %minigame4%" "&f - %minigame5%" "&f - %minigame6%" "&f - %minigame7%" "&f - %minigame8%" "" "&7Coins: &6%coins%" "&7Score: &2%score%" "&7Games Played: &9%gamesPlayed%" "" "&aClick to play!" "&7%currentPlaying% Currently playing!" -
有人可以帮我吗?
-
您是否因为这段代码而面临性能问题?
-
如果你没有任何性能问题,那么你应该没问题。也许使用 string.Join 而不是 serializeLore 方法。
标签: java replace minecraft placeholder bukkit