I simply want to ask if what I have written so far is correct and if there's any mistakes or improvements I could make that I have overseen. The Plugin is simply one that, when the Player right clicks an oak log, there is a 33% chance of them getting an apple. Simple. I'm fairly new so I apologize for anything majorly stupid! Code: @EventHandler public void onRightClick(PlayerInteractEvent e) { Player player = e.getPlayer(); Action action = e.getAction(); if(action.equals(Action.RIGHT_CLICK_BLOCK)) { e.getClickedBlock(); if (e.getClickedBlock().equals(Material.OAK_LOG)) { Random random = new Random(2); int luck = random.nextInt(2); switch(luck) { case 0: player.sendMessage("Ihr schüttelt den Baum und Äpfel fallen herunter!"); player.getInventory().addItem(Material.APPLE); case 1: player.sendMessage("Ihr schüttelt am Baum, doch nichts geschiet..."); case 2: player.sendMessage("Ihr schüttelt am Baum, doch nichts geschiet...");
@Demyxa You can use an if statement with luck == 0 and an else statement e.getClickedBlock() on its own doesn't do anything.
If you still want to use the switch-case block, you can make it so it 'falls through': Code:Java case 1:case 2: player.sendMessage("Whatever your message is");//default: default statement? idk if its necessary But really, timtower's method is more simple.
@timtower I believe this is how you meant it, I also just noticed that this part Code: player.getInventory().addItem(Material.APPLE); is marked at the "addItem" part, saying I should use an ItemStack. Can I not simply put a single Apple like this Code: if(action.equals(Action.RIGHT_CLICK_BLOCK)) { if (e.getClickedBlock().equals(Material.OAK_LOG)) { Random random = new Random(2); int luck = random.nextInt(2); if (luck == 0) { player.sendMessage("Ihr schüttelt am Baum und Äpfel fallen herunter!"); player.getInventory().addItem(Material.APPLE); } else { player.sendMessage("Ihr schüttelt am Baum, doch nichts geschieht...");
Also Code:Java random.nextInt(2); This statement gives a random Integer from 0 to below the bound int. In this case, the bound int is 2... So it'll give a number from 0 - 1. Broken English .-. EDIT: So it's a 50% chance of getting an apple with your code.
I'd say watch your indents. And I think so many nested methods are also not so beautiful. A bit depending on how the rest of the method looks like you can change your if statements a bit and the code will look much easier to read imo. Code: @EventHandler public void onRightClick(PlayerInteractEvent e) { Player player = e.getPlayer(); Action action = e.getAction(); if (!action.equals(Action.RIGHT_CLICK_BLOCK)) return; if (!e.getClickedBlock().equals(Material.OAK_LOG)) return; Random random = new Random(3); int luck = random.nextInt(3) ... And for future projects maybe keep in mind that the creation of a Random is expensive, also in comparison to the method Math.random(). I would recommend to use this method OR to have only one instance of Random for the whole class.