我正在寻找一种更好的方法来编写以下代码:
public static void initTab(Player player) {
player.getPacketSender().sendString(15002, "Achievements - " + amountCompleted(player, Difficulty.TOTAL) + "/30");
player.getPacketSender().sendString(15007, "Easy Tasks - " + amountCompleted(player, Difficulty.EASY) + "/10");
player.getPacketSender().sendString(15008, getColor(player, 0, 0)+Achievements.Tasks.TASK1.getName());
player.getPacketSender().sendString(15009, getColor(player, 1, 0)+Achievements.Tasks.TASK2.getName());
player.getPacketSender().sendString(15010, getColor(player, 2, 0)+Achievements.Tasks.TASK3.getName());
player.getPacketSender().sendString(15011, getColor(player, 3, 0)+Achievements.Tasks.TASK4.getName());
player.getPacketSender().sendString(15012, getColor(player, 4, 0)+Achievements.Tasks.TASK5.getName());
player.getPacketSender().sendString(15013, getColor(player, 5, 0)+Achievements.Tasks.TASK6.getName());
player.getPacketSender().sendString(15014, getColor(player, 6, 0)+Achievements.Tasks.TASK7.getName());
player.getPacketSender().sendString(15015, getColor(player, 7, 0)+Achievements.Tasks.TASK8.getName());
player.getPacketSender().sendString(15016, getColor(player, 8, 0)+Achievements.Tasks.TASK9.getName());
player.getPacketSender().sendString(15017, getColor(player, 9, 0)+Achievements.Tasks.TASK10.getName());
}
我正在考虑使用for循环来循环ID的(15008,15009,等等…)但我不知道如何以同样的方式循环遍历枚举值。
我说的是这个:Achievements.Tasks.TASK1.getName()
我有一个名为Tasks的enum,这里是其中一些值的示例:
TASK1(Difficulty.EASY, TaskType.GLOBAL, "Easy Test1", "Test Description.", 1, new int[]{8147, 8148}),
TASK2(Difficulty.EASY, TaskType.GLOBAL, "Easy Test2", "Test Description.", 1, new int[]{8150, 8151}),
TASK3(Difficulty.EASY, TaskType.GLOBAL, "Easy Test3", "Test Description.", 1, new int[]{8153, 8154}),
TASK4(Difficulty.EASY, TaskType.GLOBAL, "Easy Test4", "Test Description.", 1, new int[]{8156, 8157}),
TASK5(Difficulty.EASY, TaskType.GLOBAL, "Easy Test5", "Test Description.", 1, new int[]{8159, 8160}),
getName()获取值中的第一个字符串:"Easy Test1"
我想知道的:一种简单的方法来循环遍历枚举值,这样我就可以在几行代码中使用getName()方法来获取所有的值。
我需要循环遍历这个语句:
player.getPacketSender().sendString(15008, getColor(player, 0, 0)+Achievements.Tasks.TASK1.getName());
我需要知道的是如何通过这个循环:
Achievements.Tasks.TASK#.getName()
这个问题不是重复的,因为我要求循环遍历两个不同的东西。我需要同时循环枚举和int(15008, 15009,等等)。不仅仅是枚举,也不仅仅是整型。我可以将枚举的for循环嵌套在int型的for循环中吗?
参见Oracle Documentation: All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.
如果这是你想要的,你可以这样做:
class EnumLoop {
enum Color {RED, BLUE, GREEN};
public static void main(String[] args) {
for (Color c : Color.values()) {
System.out.println(c.name());
}
}
}