Reputation: 61
Hello im coding a plugin for the game minecraft using Bukkit. Basically when a player right clicks with a egg that egg has a specific durability. The durability does not change at all because the event is called every time someone does this and its individual. The code i currently have is not done but this is basically it:
if (e.getItem().getTypeId() == 383) {
if (!worldguardPlugin.canBuild(e.getPlayer(), loc)) {
e.setCancelled(true);
e.getPlayer().sendMessage(
ChatColor.YELLOW
+ "You cant use spawner eggs in this region!");
return;
}
switch (e.getItem().getDurability()) {
case 2:
expOrb(e);
break;
case 9:
painting(e);
break;
case 20:
primedTnt(e);
break;
case 40:
minecart(e);
break;
case 41:
boat(e);
break;
case 50:
creeper(e);
break;
case 51:
skeleton(e);
break;
case 52:
spider(e);
break;
case 53:
giant(e);
break;
case 54:
zombie(e);
break;
case 55:
slime(e);
break;
case 56:
ghast(e);
break;
case 57:
pigman(e);
break;
case 58:
enderman(e);
break;
case 59:
cavespider(e);
break;
case 60:
silverfish(e);
break;
case 61:
blaze(e);
break;
case 62:
cube(e);
break;
case 63:
dragon(e);
break;
case 90:
pig(e);
break;
case 91:
sheep(e);
break;
case 92:
cow(e);
break;
case 93:
chicken(e);
break;
case 94:
squid(e);
break;
case 95:
wolf(e);
break;
case 96:
moosh(e);
break;
case 97:
snowGolem(e);
break;
case 98:
ocelot(e);
break;
case 99:
ironGolem(e);
break;
case 120:
villager(e);
break;
case 200:
crystal(e);
break;
default:
break;
}
}
}
Since I'm using break, all of the methods i made won't be called correct? That would cause lots of pointless code being executed and wasted performance, and the entire point of this design was for better work flow.
Upvotes: 1
Views: 3463
Reputation: 471
In your case, only the item that specifically matches the switched statements executes because of the breaks. If there were no breaks though, the first match would be called, and ALL subsequent. For example, the code:
System.out.println("starting");
int i = 2;
switch (i) {
case 1:
System.out.println(1);
case 2:
System.out.println(2);
case 3:
System.out.println(3);
}
System.out.println("finished");
yields the following output:
starting
2
3
finished
Upvotes: 2
Reputation: 3848
The inefficiency is where you need to check for all the cases unless you get to the ones at the end, like 200 in this case. You need to reorganize the decision making process so that it at least runs faster for more frequent cases. Although the switch statement is optimised by compiler, but can't do much if there are so many things to compare against.
From the switch statement's perspective, you are right: It short circuits if it gets to the break statement.
Upvotes: 0
Reputation: 106470
Your assumption is correct. Only the code that meets the specific switch
case will be executed. After all, a switch statement is a substitute for a giant if-else if-else
block.
Upvotes: 2