I have a series of if statements that all seem to work except for when I reach two arguments after a command (Minecraft Bukkit server/API). With two arguments it returns false no matter what. I am using the command /jukebox play 13 to test it.
Current code:
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String commandlabel, String[] args) {
Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("jukebox")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GOLD + "** " + ChatColor.AQUA + "Jukebox version " + pdFile.getVersion() + ChatColor.GOLD + " **\n" + ChatColor.RED + "Usage: " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)");
return true;
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
if (args.length == 2 && (args[0].equalsIgnoreCase("play"))) {
if (args[1].equalsIgnoreCase("13")) {
p.playEffect(p.getLocation(), Effect.RECORD_PLAY, 2256);
sender.sendMessage(ChatColor.AQUA + "Now playing " + ChatColor.GREEN + "13" + ChatColor.AQUA + ".");
return true;
}
else {
sender.sendMessage(ChatColor.AQUA + "Please enter a valid track name.");
}
}
}
}
return false;
}
}
Does anyone see why it is returning false? Just as a side note, if you see anything in here that could be coded more efficiently, feel free to suggest that too.
Your indention is throwing you off. Your closing braces are in the wrong place. Your args.length == 2 check is nested within the args.length ==1 check. At the minimum you will have to :
1. add a closing brace before the if statement for args.length == 2 check
2. delete a closing brace before the return false statement.
It looks like a bracket is in the wrong place:
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
should be:
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
}
notice the } at the end. Right now, you're code is doing this:
if(args.length == 1){
if(args.length > 1 && args[0].equalsIgnoreCase("play")){
}
}
which will always return false, as args cannot have a length of one, and also have a length greater than one
As other's have said, you've gotten the bracket nesting wrong, and your incorrect code indentation is misleading you.
Advice ... if you want to avoid this kind of problem in the future:
Pay more attention to your code style in general, and particularly indentation. It makes your code easier for >>you<< to read.
Use an IDE ... or a smart editor that is capable of correctly indenting Java. And make sure that you make use of its auto-indenting functionality.
If possible, configure your IDE / editor to use space characters not TAB characters for code indentation. If your code has TAB characters in it, then it will look different (i.e. incorrectly indented) on different systems.
As shoover pointed out the } for the if (args.length == 1) statement was in the wrong place.
The new code is:
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command cmd, String commandlabel, String[] args) {
Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("jukebox")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GOLD + "** " + ChatColor.AQUA + "Jukebox version " + pdFile.getVersion() + ChatColor.GOLD + " **\n" + ChatColor.RED + "Usage: " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)");
return true;
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("play")) {
String recordNames = "Stop, 13, Cat, Blocks, Chirp, Far, Mall, Mellohi, Stal, Strad, Ward, 11, Wait";
String regex = "\\[|\\]";
recordNames = recordNames.replaceAll(regex, "");
sender.sendMessage(ChatColor.AQUA + "Track selection: " + ChatColor.GREEN + recordNames + "\n" + ChatColor.AQUA + "Type " + ChatColor.LIGHT_PURPLE + "/jukebox play (track)" + ChatColor.AQUA + " to play a track.");
return true;
}
}
if (args.length > 1 && (args[0].equalsIgnoreCase("play"))) {
if (args[1].equalsIgnoreCase("13")) {
p.playEffect(p.getLocation(), Effect.RECORD_PLAY, 2256);
sender.sendMessage(ChatColor.AQUA + "Now playing " + ChatColor.GREEN + "13" + ChatColor.AQUA + ".");
return true;
}
else {
sender.sendMessage(ChatColor.AQUA + "Please enter a valid track name.");
return true;
}
}
}
return false;
Related
I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.
I have this challenge to create a facebook-like counter that will show how many people liked a post. I'm relatively new to Java, but have managed to do it. My question is - Is there a more practical and short way of writing the below method?
im just using a simple static array in the Main called users[] with some names in it.
public static void facebookCounter(String users[])
{
if(users.length == 1)
{
System.out.println(users[0] + " liked this");
}
else if(users.length == 2)
{
System.out.println(users[0] + " " + users[1] + " liked this.");
}
else if(users.length > 2)
{
System.out.println(users[0] + " " + users[1] + " and " + (users.length-2) + " others liked this");
}
}
Sorry if my pasted code is not formatted well, I pasted it from my intelliJ
Thanks to anyone who has any ideas!
Another approach could be using switch statement rather than if/else:
public static void facebookCounter(String users[]) {
switch (users.length) {
case 0: break;
case 1:
System.out.println(users[0] + " liked this");
break;
case 2:
System.out.println(users[0] + " " + users[1] + " liked this.");
break;
default:
System.out.println(users[0] + " " + users[1] + " and " + (users.length-2) + " others liked this");
}
}
My suggestion is to stream the first 1 or 2 array items (depending on array's length), collect to String with a joining space char. then, add appropriate suffix:
public static void facebookCounter(String users[])
{
String msg = IntStream.range(0, Math.min(2, users.length))
.mapToObj(i -> users[i])
.collect(Collectors.joining(" "));
if (users.length > 2) msg += " and " + (users.length-2) + " others";
msg += " liked this";
System.out.println(msg);
}
EDIT:
the suffix can be specified in the joining() method:
System.out.println(
IntStream.range(0, Math.min(2, users.length))
.mapToObj(i -> users[i])
.collect(Collectors.joining(" ", "",
users.length > 2 ? " and " + (users.length-2) + " others liked this" : " liked this"
)
)
);
I asked a similar question to this today, but I need help with further development.
The HashMaps:
Map<UUID, UUID> duels = new HashMap<UUID, UUID>();
Map<UUID, UUID> selecting = new HashMap<UUID, UUID>();
The command:
if (cmd.getName().equalsIgnoreCase("duel")) {
if (!(args.length == 1)) {
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " Usage: /duel <Player>");
return true;
} else if (args.length == 1) {
Player p = Bukkit.getServer().getPlayer(args[0]);
if (p != null) {
if (p.equals(sender)) {
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " You cannot duel yourself!");
return true;
} else {
if (duels.containsKey(p) || duels.containsKey(sender)) {
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "] " + ChatColor.RED + "Either you or " + ChatColor.BLUE + p.getName() + ChatColor.RED + " are already in a duel!");
return true;
} else
openKitSelector((Player) sender);
selecting.put(p.getUniqueId(), ((Player) sender).getUniqueId());
The KitSelector inventory:
public void openKitSelector(Player p) {
Inventory selector = Bukkit.createInventory(p, 9, ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "KitSelector" + ChatColor.DARK_RED + "]");
ItemStack diamond = new ItemStack(Material.DIAMOND_SWORD);
ItemMeta diamondMeta = diamond.getItemMeta();
diamondMeta.setDisplayName(ChatColor.DARK_AQUA + "Diamond Kit");
diamond.setItemMeta(diamondMeta);
ItemStack iron = new ItemStack(Material.IRON_SWORD);
ItemMeta ironMeta = iron.getItemMeta();
ironMeta.setDisplayName(ChatColor.DARK_GREEN + "Iron Kit");
iron.setItemMeta(ironMeta);
selector.setItem(0, diamond);
selector.setItem(1, iron);
p.openInventory(selector);
}
The Accept/Deny inventory:
private void openGUI(Player player) {
Inventory inv = Bukkit.createInventory(null, 9, ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "DuelRequest" + ChatColor.DARK_RED + "]");
ItemStack accept = new ItemStack(Material.EMERALD_BLOCK);
ItemMeta acceptMeta = accept.getItemMeta();
ItemStack decline = new ItemStack(Material.REDSTONE_BLOCK);
ItemMeta declineMeta = decline.getItemMeta();
acceptMeta.setDisplayName(ChatColor.GREEN + "Accept!");
accept.setItemMeta(acceptMeta);
declineMeta.setDisplayName(ChatColor.RED + "Decline!");
decline.setItemMeta(declineMeta);
inv.setItem(3, accept);
inv.setItem(5, decline);
player.openInventory(inv);
}
So what I need to happen is, when someone types /duel <player> , they will get an inventory up with a selection of items that will give them kits, which I have done correctly and tested. Then when they select a kit, the target of the /duel command will get an inventory with an accept item and decline item.
I got everything working up to the part were the target gets the inventory for accept or deny as I am not really experienced with HashMaps, and I am a little confused.
If you wanted to get the target of a duel request from the selecting HashMap, you could use:
UUID id = selecting.get(player.getUniqueId());
Player target = Bukkit.getPlayer(id);
So, if you wanted to open the kit selector for the target, you could use:
//get the UUID of the Player that is being targeted by the Player player
UUID id = selecting.get(player.getUniqueId());
//get the target Player from the UUID above
Player target = Bukkit.getPlayer(id);
//open the kit selector for the target Player above
openKitSelector(target);
To open the target's inventory after the duel requester has selected their kit, you would have to listen for InventoryCloseEvent:
#EventHandler
public void inventoryClose(InventoryCloseEvent e){
//called when a player closes their inventory
}
So, your code could look like this:
#EventHandler
public void inventoryClose(InventoryCloseEvent e){
//check if the inventory is the duel inventory
if(e.getInventory().getName().equals(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "DuelRequest" + ChatColor.DARK_RED + "]"){
//get the player who opened the inventory
Player p = (Player) e.getWhoClicked();
//now, check if the selecting HashMap contains the Player above
if(selecting.containsKey(p.getUniqueId())){
//get the target of the duel
Player target = Bukkit.getPlayer(selecting.get(p.getUniqueId()));
//open the kit selector for the target Player above
openKitSelector(target);
//now, remove the target's, and the sender's UUID from the selecting
//HashMap, to make sure that we don't accidentally open the kit
//selector for a player who is currently in a duel.
selecting.remove(p.getUniqueId());
//make sure the selecting HashMap contains the target's UUID before
//attempting to remove it
if(selecting.containsKey(target.getUniqueId())){
selecting.remove(target.getUniqueId());
}
}
}
}
If you wanted to make sure that the player clicks something in the inventory, you could use InventoryClickEvent:
#EventHandler
public void inventoryClick(InventoryClickEvent e){
//called when a player clicks something in a inventory
}
Also, you will have to switch around the order in which items are in the HashMap. Instead of using the target as the key, use the sender as the key:
selecting.put(((Player) sender).getUniqueId(), p.getUniqueId());
So, your onCommand could look like this:
if(cmd.getName().equalsIgnoreCase("duel")){
if(!(args.length == 1)){
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " Usage: /duel <Player>");
return true;
}
else if (args.length == 1){
Player p = Bukkit.getServer().getPlayer(args[0]);
if(p != null){
if(p.equals(sender)){
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " You cannot duel yourself!");
return true;
}
else{
if(duels.containsKey(p) || duels.containsKey(sender)){
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "] " + ChatColor.RED + "Either you or " + ChatColor.BLUE + p.getName() + ChatColor.RED + " are already in a duel!");
return true;
}
else{
openKitSelector((Player) sender);
//this line was changed from
//selecting.put(p.getUniqueId(), ((Player) sender).getUniqueId())
//to the new value, with the sender as the key,
//and the target as the value.
selecting.put(((Player) sender).getUniqueId(), p.getUniqueId());
}
}
}
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Getting this syntax error when coding, I can't seem to find the source of the problem if any one knows place comment as quickly as possible thanks.
package me.carwyn123;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
org.bukkit.plugin.java.JavaPlugin;
public class Staffviewer extends JavaPlugin {
#Override
public void onEnable() {
getLogger().info("Staffviewer plugin now enabled / plugin made by carwyn123");
getConfig().options().copyDefaults(true);
saveConfig();
}
#Override
public void onDisable() {
getLogger().info("Staffviewer as been disabled / plugin made by carwyn123");
saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String Label, String[] args) {
// the staff list code
if (cmd.getName().equalsIgnoreCase("staff") && sender instanceof Player) {
if ( !sender.hasPermission("staffviewer.staff")) {
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You don't have permission");
return true;
}
Player player = (Player) sender;
player.sendMessage(ChatColor.AQUA + "================================");
player.sendMessage(ChatColor.GOLD + " Staff members");
player.sendMessage(ChatColor.AQUA + "================================");
player.sendMessage(ChatColor.GREEN + getConfig().getString("staffmembers"));
player.sendMessage(ChatColor.AQUA + "================================");
player.sendMessage(ChatColor.AQUA + getConfig().getString("staffmembers"));
return true;
}
// staff help code
if (cmd.getName().equalsIgnoreCase("staffhelp") && sender instanceof Player) {
if ( !sender.hasPermission("staffviewer.help")) {
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You don't have permission");
return true;
}
Player player = (Player) sender;
player.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "Here is the list of commands" );
player.sendMessage(ChatColor.GOLD + "---------------------------------");
player.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "/staff : gives the list of staff");
player.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "/staffadd: adds staff to the list, using config allows for more design");
player.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "/staffhelp: gets you to this page");
player.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "/staffinfo: gives you information about the plugin");
player.sendMessage(ChatColor.GOLD + "---------------------------------");
return true;
}
// staff information
if (cmd.getName().equalsIgnoreCase("staffinfo") && sender instanceof Player) {
if( !sender.hasPermission("staffviewer.info")) {
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You don't have permission");
return true ;
}
Player player = (Player) sender;
player.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "Here you will find information about the plugin");
player.sendMessage(ChatColor.AQUA + "--------------------------------------------------------------------");
player.sendMessage(ChatColor.GOLD + " This plugin was made by carwyn123");
player.sendMessage(ChatColor.GOLD + " If you find any bugs, please report as a ticked or commet on bukkit.dev");
player.sendMessage(ChatColor.GOLD + " Thanks for downloading this plugin, from the team");
player.sendMessage(ChatColor.AQUA + "--------------------------------------------------------------------");
return true;
}
// staff add code
if (cmd.getName().equalsIgnoreCase("staffadd")); {
if ( !sender.hasPermission("staffviewer.add")) {
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You don't have permission");
return true ;
}
if (args.length == 0) {
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You can't add know one");
return true;
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < args.length; i++) {
str.append(args[i] + " ");
}
String staffmembers = str.toString();
getConfig().set("staffmembers", staffmembers);
saveConfig();
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You have added a staff member");
return true;
// staff line editor
}
if (cmd.getName().equalsIgnoreCase("staffedit")); {
if (!sender.hasPermission("staffviewer.edit")) {
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You don't have permission");
return true;
}
if (args.length == 0) {
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You need to add a message");
return true;
}
StringBuilder str1 = new StringBuilder();
for (int i = 0; i < args.length; i++) {
str1.append(args[i] + " ");
}
String staffedit = str1.toString();
getConfig().set("endline", staffedit);
saveConfig();
sender.sendMessage(ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA + "You have added a message at the end");
return true;
}
}
The problem has been happening for about 2 hours now. I have searched a lot of sources on the internet and this seems to be a well known problem with people that are new to coding.
Add import declaration for org.bukkit.plugin.java.JavaPlugin;, change it to
import org.bukkit.plugin.java.JavaPlugin;
And add a } at the end to complete the class.
You had several errors in your code and you wrote ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA several times, so I made a prefix variable for it.
Your final code is this:
package me.carwyn123;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class Staffviewer extends JavaPlugin {
String prefix=ChatColor.GOLD + "[StaffViewer]" + ChatColor.AQUA;
#Override
public void onEnable() {
getLogger().info("Staffviewer plugin now enabled / plugin made by carwyn123");
getConfig().options().copyDefaults(true);
saveConfig();
}
#Override
public void onDisable() {
getLogger().info("Staffviewer as been disabled / plugin made by carwyn123");
saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String Label, String[] args) {
// the staff list code
if (cmd.getName().equalsIgnoreCase("staff") && sender instanceof Player) {
if ( !sender.hasPermission("staffviewer.staff")) {
sender.sendMessage(prefix + "You don't have permission");
return true;
}
Player player = (Player) sender;
player.sendMessage(ChatColor.AQUA + "================================");
player.sendMessage(ChatColor.GOLD + " Staff members");
player.sendMessage(ChatColor.AQUA + "================================");
player.sendMessage(ChatColor.GREEN + getConfig().getString("staffmembers"));
player.sendMessage(ChatColor.AQUA + "================================");
player.sendMessage(ChatColor.AQUA + getConfig().getString("staffmembers"));
return true;
}
// staff help code
if (cmd.getName().equalsIgnoreCase("staffhelp") && sender instanceof Player) {
if ( !sender.hasPermission("staffviewer.help")) {
sender.sendMessage(prefix + "You don't have permission");
return true;
}
Player player = (Player) sender;
player.sendMessage(prefix + "Here is the list of commands" );
player.sendMessage(ChatColor.GOLD + "---------------------------------");
player.sendMessage(prefix + "/staff : gives the list of staff");
player.sendMessage(prefix + "/staffadd: adds staff to the list, using config allows for more design");
player.sendMessage(prefix + "/staffhelp: gets you to this page");
player.sendMessage(prefix + "/staffinfo: gives you information about the plugin");
player.sendMessage(ChatColor.GOLD + "---------------------------------");
return true;
}
// staff information
if (cmd.getName().equalsIgnoreCase("staffinfo") && sender instanceof Player) {
if( !sender.hasPermission("staffviewer.info")) {
sender.sendMessage(prefix + "You don't have permission");
return true ;
}
Player player = (Player) sender;
player.sendMessage(prefix + "Here you will find information about the plugin");
player.sendMessage(ChatColor.AQUA + "--------------------------------------------------------------------");
player.sendMessage(ChatColor.GOLD + " This plugin was made by carwyn123");
player.sendMessage(ChatColor.GOLD + " If you find any bugs, please report as a ticked or commet on bukkit.dev");
player.sendMessage(ChatColor.GOLD + " Thanks for downloading this plugin, from the team");
player.sendMessage(ChatColor.AQUA + "--------------------------------------------------------------------");
return true;
}
// staff add code
if (cmd.getName().equalsIgnoreCase("staffadd")){
if ( !sender.hasPermission("staffviewer.add")) {
sender.sendMessage(prefix + "You don't have permission");
return true ;
}
if (args.length == 0) {
sender.sendMessage(prefix + "You can't add know one");
return true;
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < args.length; i++) {
str.append(args[i] + " ");
}
String staffmembers = str.toString();
getConfig().set("staffmembers", staffmembers);
saveConfig();
sender.sendMessage(prefix + "You have added a staff member");
return true;
}
// staff line editor
if (cmd.getName().equalsIgnoreCase("staffedit")){
if (!sender.hasPermission("staffviewer.edit")) {
sender.sendMessage(prefix + "You don't have permission");
return true;
}
if (args.length == 0) {
sender.sendMessage(prefix + "You need to add a message");
return true;
}
StringBuilder str1 = new StringBuilder();
for (int i = 0; i < args.length; i++) {
str1.append(args[i] + " ");
}
String staffedit = str1.toString();
getConfig().set("endline", staffedit);
saveConfig();
sender.sendMessage(prefix + "You have added a message at the end");
return true;
}
return false;
}
}
Basically, I have code that uses the same few lines in different scenarios, and it makes the code a bit messy (especially since I probably overcomplicated what I made, but that's another issue). What I wanted to do is store that piece of code as another function and calling it in the longer one. WHich should work as far as I know, except, the longer function has variables that aren't set in the shorter one, and if they were, I'm pretty sure it would change the final result of the function.
Here is the longer code:
public static void combat(Character a,Character b){
int battleturn = 1;
int maxTurns=20;
int draw1 = 0;
//stop after 20 turns, or stop when one player has 0 HP.
while (a.health > 0 && b.health > 0 && maxTurns > 0){
/* run a round of combat*/
if (b.health < 0.25 * b.maxHealth){
if (b.getFlee(a)){
System.out.println(">>>>>>>>>>The enemy has fled successfully<<<<<<<<<<");
break;
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + "health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}
}
As you can see there is a part of code that is repeated, and that is.
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
It won't compile if I set that chunk of code as a method, because it doesn't have the variables battleturn, maxturns, draw1, but if I put them in there, the amount of battle turns messes up.
Any ideas?
Java applications should be modular: each class fulfilling its own function, each method generally performing a single operation.
In a method you can use either class variables or its own local variables.
If you need several methods work with the same data, it should either be part of a class (instance and/or static variables) or passed to each method as parameters.
Make sure that you do not define class variables in a method. This will create local variables that will shadow class variables.
This might help you accomplish what you're trying to do.
private static void reportDamage(Character a,
Character b) {
System.out.println(a.name + " dealt "
+ a.combatRound(b) + " damage to " + b.name
+ "." + " Enemy has " + b.getHealth() + "/"
+ b.getMaxHealth() + " health.");
}
I suggest changing your combat method like this.
int battleturn = 0;
int maxTurns = 20;
// stop after 20 turns, or stop when one player has 0
// HP.
Scanner input = new Scanner(System.in);
try {
while (a.health > 0 && b.health > 0
&& battleturn < maxturn) {
battleturn++;
/* run a round of combat */
if (b.getFlee(a)) {
System.out.println(">>>>>>>>>>"
+ "The enemy has fled successfully"
+ "<<<<<<<<<<");
break;
} else {
System.out.println("Battle turn "
+ battleturn + ", <attack> or <flee>?");
boolean isFlee = false;
boolean isAttack = false;
String move = input.next();
for (;;) {
isAttack = "attack".equalsIgnoreCase(move);
isFlee = "flee".equalsIgnoreCase(move);
if (isFlee || isAttack) {
break;
}
System.out.println("Error: "
+ "Please input <attack> or <flee>.");
move = input.next();
}
if (isAttack) {
reportDamage(a, b);
reportDamage(b, a);
} else { // isFlee
if (a.getFlee(b)) {
System.out.println(">>>>>>>>>>"
+ "You have fled successfully"
+ "<<<<<<<<<<");
break;
} else {
// b is fleeing.
// reportDamage(a, b);
reportDamage(b, a);
}
}
}
}
} finally {
input.close();
}