So I have some code which gives an error when executing...
if (!(sender.hasPermission("nexodus.an"))) {
player.sendMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " You can not do this command!");
return true;
} else if (args.length == 0) {
player.sendMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " You must specify a predetermined message to broadcast!");
player.sendMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " 1: Server Restarting");
player.sendMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " 2: Login servers are currently down!");
player.sendMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " 3: Reloading for GameModes");
return true;
} else if (args.length > 1) {
if (args[0].equalsIgnoreCase("1")) {
Bukkit.broadcastMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " NexodusMC will be restarting in 5 seconds.");
} else if (args[0].equalsIgnoreCase("2")) {
Bukkit.broadcastMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " Login servers are currently down. Logging off my prevent you from getting back on, sorry!");
//Line above is line 53 ||
} else if (args[0].equalsIgnoreCase("3")) {
Bukkit.broadcastMessage(ChatColor.BLACK + "[" + ChatColor.DARK_PURPLE + "NexodusMC" + ChatColor.BLACK + "]" + ChatColor.GREEN + " Server reload due to adding/removing/editing gamemodes!");
}
return true;
}
Here is my error log.
org.bukkit.command.CommandException: Unhandled exception executing command 'an' in plugin NexodusHub vSwag
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46)
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:192)
at org.bukkit.craftbukkit.v1_6_R3.CraftServer.dispatchCommand(CraftServer.java:523)
at net.minecraft.server.v1_6_R3.PlayerConnection.handleCommand(PlayerConnection.java:959)
at net.minecraft.server.v1_6_R3.PlayerConnection.chat(PlayerConnection.java:877)
at net.minecraft.server.v1_6_R3.PlayerConnection.a(PlayerConnection.java:834)
at net.minecraft.server.v1_6_R3.Packet3Chat.handle(SourceFile:49)
at net.minecraft.server.v1_6_R3.NetworkManager.b(NetworkManager.java:296)
at net.minecraft.server.v1_6_R3.PlayerConnection.e(PlayerConnection.java:116)
at net.minecraft.server.v1_6_R3.ServerConnection.b(SourceFile:37)
at net.minecraft.server.v1_6_R3.DedicatedServerConnection.b(SourceFile:30)
at net.minecraft.server.v1_6_R3.MinecraftServer.t(MinecraftServer.java:592)
at net.minecraft.server.v1_6_R3.DedicatedServer.t(DedicatedServer.java:227)
at net.minecraft.server.v1_6_R3.MinecraftServer.s(MinecraftServer.java:488)
at net.minecraft.server.v1_6_R3.MinecraftServer.run(MinecraftServer.java:421)
at net.minecraft.server.v1_6_R3.ThreadServerApplication.run(SourceFile:583)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1
at me.Bling.NexodusMain.Main.onCommand(Main.java:53) # 53 is the error line.
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44)
... 15 more
What am I doing wrong?
Fixed
Changed
} else if (args.length > 1) {
to
} else if (args.length > 0) {
Related
My database has "diary" table and "food" table. In diary table I have following columns: date, food1,food2, ...food10. In food table I have: id, name, allergen1, allergen2, allergen3. So basically you log up to 10 foods a day to diary. Now I'm trying to build a query which would let me find last date that I've eaten food with allergen3. So that's the query I came up with, which you probably know is not working ;-)
Cursor findDateRes = db.rawQuery("SELECT date(" + DIARY_COL_DATE + ") FROM " + DIARY_TABLE
+ " INNER JOIN " + FOOD_TABLE + " food1 ON (food1." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F1 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food2 ON (food2." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F2 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food3 ON (food3." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F3 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food4 ON (food4." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F4 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food5 ON (food5." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F5 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food6 ON (food6." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F6 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food7 ON (food7." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F7 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food8 ON (food8." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F8 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food9 ON (food9." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F9 + ")"
+ " INNER JOIN " + FOOD_TABLE + " food10 ON (food10." + FOOD_COL_1 + " = " + DIARY_TABLE + "." + DIARY_COL_F10 +
") WHERE 1 NOT IN (food1." + FOOD_COL_5 +
",food2." + FOOD_COL_5 +
",food3." + FOOD_COL_5 +
",food4." + FOOD_COL_5 +
",food5." + FOOD_COL_5 +
",food6." + FOOD_COL_5 +
",food7." + FOOD_COL_5 +
",food8." + FOOD_COL_5 +
",food9." + FOOD_COL_5 +
",food10." + FOOD_COL_5 +
") ORDER BY date(" + DIARY_COL_DATE + ") ASC LIMIT 1", null);
"FOOD_COL_1" stands for id and "FOOD_COL_5" stands fro allergen3.
Thank you for looking. Any input will be appreciated.
I first created the inventory that will be opened:
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);
}
Then I created the command that will be run:
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 {
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.GREEN + " You sent a duel request to " + ChatColor.BLUE + p.getName());
p.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.GREEN + " You recieved a duel request from " + ChatColor.BLUE + sender.getName());
openGUI(p);
}
}
} else {
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " Player not found!");
}
}
return true;
I Then created an event that is called when a players clicks their inventory.
#SuppressWarnings("deprecation")
#EventHandler
private void onClick(InventoryClickEvent e) {
if (!ChatColor.stripColor(e.getInventory().getName()).equalsIgnoreCase("[DuelRequest]"))
return;
Player player = (Player) e.getWhoClicked();
e.setCancelled(true);
switch (e.getCurrentItem().getType()) {
case EMERALD_BLOCK:
player.closeInventory();
player.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.GREEN + " You accepted the request");
player.getInventory().setItem(0, new ItemStack(Material.DIAMOND_SWORD));
player.getInventory().setItem(1, new ItemStack(Material.BOW));
player.getInventory().setItem(2, new ItemStack(Material.GOLDEN_APPLE, 2));
player.getInventory().setItem(3, new ItemStack(Material.ARROW, 32));
player.getInventory().setHelmet(new ItemStack(Material.DIAMOND_HELMET));
player.getInventory().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE));
player.getInventory().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS));
player.getInventory().setBoots(new ItemStack(Material.DIAMOND_BOOTS));
break;
case REDSTONE_BLOCK:
player.closeInventory();
player.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " You denied the request!");
break;
default:
player.closeInventory();
break;
}
}
So, what i want to happen is..
When a player types /duel , the (target) will have an inventory opened in front of them with an option to accept or decline the duel request. I have tested this and it works as expected. If they decline they will receive a message telling them they rejected it, if they accept they will be given a Kit to duel with. This also works as expected. However, i need to be able to give the sender of the /duel command the same kit, but i don't know how to. So... When the (target) accepts the duel, both players will receive a kit so they can both fight.
Is there a way of calling for the onClick event inside the onCommand?
Or is there a way to contact the sender of the command from inside the onClick event?
I am average with Bukkit coding but obviously still have a lot to learn so any help/constructive criticism is always helpful!
You could use a HashMap, to store the player that sent the duel request to a player:
Map<UUID, UUID> duels = new HashMap<UUID, UUID>();
HashMaps are used to store a value for another value, it's effectively a large collection of variables.
When the sender runs the command, you could use:
duels.put(target.getUniqueId(), sender.getUniqueId());
So, when the target accepts the duel, you could get the sender of the request with:
duels.get(target.getUniqueId());
Here's what your onCommand() could look like:
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 {
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.GREEN + " You sent a duel request to " + ChatColor.BLUE + p.getName());
p.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.GREEN + " You recieved a duel request from " + ChatColor.BLUE + sender.getName());
openGUI(p);
//Put the player in the HashMap here
duels.put(p.getUniqueId(), ((Player) sender).getUniqueId());
}
}
} else {
sender.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " Player not found!");
}
}
return true;
And your onClick() could look like this:
#SuppressWarnings("deprecation")
#EventHandler
//It's better if you make your events public
//and not private
public void onClick(InventoryClickEvent e) {
if (!ChatColor.stripColor(e.getInventory().getName()).equalsIgnoreCase("[DuelRequest]"))
return;
Player player = (Player) e.getWhoClicked();
e.setCancelled(true);
//get the UUID stored in the duels HashMap for the player's UUID as a key
UUID uuid = duels.get(player.getUniqueId());
//Get the challenger from the UUID above
Player challenger = Bukkit.getPlayer(uuid);
switch (e.getCurrentItem().getType()) {
case EMERALD_BLOCK:
player.closeInventory();
player.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.GREEN + " You accepted the request");
player.getInventory().setItem(0, new ItemStack(Material.DIAMOND_SWORD));
player.getInventory().setItem(1, new ItemStack(Material.BOW));
player.getInventory().setItem(2, new ItemStack(Material.GOLDEN_APPLE, 2));
player.getInventory().setItem(3, new ItemStack(Material.ARROW, 32));
player.getInventory().setHelmet(new ItemStack(Material.DIAMOND_HELMET));
player.getInventory().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE));
player.getInventory().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS));
player.getInventory().setBoots(new ItemStack(Material.DIAMOND_BOOTS));
//give the kit to the challenger here
//Maybe make a method, giveKit(Player p), to clean up your code
//Then you could run giveKit(challenger) and giveKit(player)
break;
case REDSTONE_BLOCK:
player.closeInventory();
player.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + " You denied the request!");
//tell the challenger that player denied their duel request
challenger.sendMessage(ChatColor.DARK_RED + "[" + ChatColor.DARK_GREEN + "HuntsCraft" + ChatColor.DARK_RED + "]" + ChatColor.RED + player.getName + " denied your duel request");
break;
default:
player.closeInventory();
break;
}
}
If you wanted to check if a UUID exists in the HashMap, you could use duels.containsKey(uuid)
Make sure to never store Player objects inside of HashMaps, because it can cause memory leaks if the player leaves the server, for instance. The best way to store player information is by storing their UUID, or by storing their username.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have read several posts suggesting to clear a JLabel (displayEntered) on a panel (display) with text by using the setText(" "). However, I have tried this and the outcome is it is just posting the array entered twice and does not clear the first set. I have an action shown below when a button is pressed both times; the first is to enter the data entered (I have the same code 4 times for the 4 different possible objects to enter but just put in the one since it's basically the same), which works fine and the second is to remove a specific one shown. My code is long, so am just putting that in. If someone wants something else please let me know. Thanks, I'd appreciate any input!
//adds the Herb data to the Array and list
enterHerbData.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Enter")){
Name = NameTxt.getText();
Colors = ColorTxt.getText();
ID = (int) IDCmbo.getSelectedItem();
Flavor = FlavorTxt.getText();
if(((String) MedicinalCmbo.getSelectedItem()).equals("Yes"))
Medicinal = true;
else
Medicinal = false;
if(((String) SeasonalCmbo.getSelectedItem()).equals("Yes"))
Seasonal = true;
else
Seasonal = false;
plants[count] = new Herb(Name, ID, Colors, Flavor, Medicinal, Seasonal);
String displayArraytemp = " ";
if(plants[count] != null){
if(plants[count] instanceof Flower){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Flower)plants[count]).getColor() + ", " + ((Flower)plants[count]).getSmell() + ", Thorny: " + ((Flower)plants[count]).getThorns() + "\n");
}
else if(plants[count] instanceof Fungus){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Fungus)plants[count]).getColor() + ", Poisonous: " + ((Fungus)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Weed){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Weed)plants[count]).getColor() + ", Edible: " + ((Weed)plants[count]).getEdible() + ", Medicinal: " + ((Weed)plants[count]).getMedicinal() + ", Poisonous: " + ((Weed)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Herb){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Herb)plants[count]).getColor() + ", " + ((Herb)plants[count]).getFlavor() + ", Medicinal: " + ((Herb)plants[count]).getMedicinal() + ", Poisonous: " + ((Herb)plants[count]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp).
append("<br> ");
displayArray = sb.toString();
}
displayEntered.setText(displayArray);
count++;
frameB.setVisible(false);
}
}
});
//removes the data to the Array and panel
ActionListener RemoveAction = new ActionListener(){
#Override
public void actionPerformed(ActionEvent RemoveAction){
if(RemoveAction.getActionCommand().equals("Enter")){
if((Btn1).isSelected()){
String displayArraytemp2 = " ";
if(count >= 1){
for(int n = 0; n < count; n++){
plants[n] = plants[n+1];
}
count--;
frameB.setVisible(false);
displayEntered.setOpaque(true);
for(int n = 0; n < 25; n++){
if(plants[n] != null){
if(plants[n] instanceof Flower){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Flower)plants[n]).getColor() + ", " + ((Flower)plants[n]).getSmell() + ", Thorny: " + ((Flower)plants[n]).getThorns() + "\n");
}
else if(plants[n] instanceof Fungus){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Fungus)plants[n]).getColor() + ", Poisonous: " + ((Fungus)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Weed){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Weed)plants[n]).getColor() + ", Edible: " + ((Weed)plants[n]).getEdible() + ", Medicinal: " + ((Weed)plants[n]).getMedicinal() + ", Poisonous: " + ((Weed)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Herb){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Herb)plants[n]).getColor() + ", " + ((Herb)plants[n]).getFlavor() + ", Medicinal: " + ((Herb)plants[n]).getMedicinal() + ", Poisonous: " + ((Herb)plants[n]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp2).
append("<br> ");
displayArray = sb.toString();
}
}
}
displayEntered.setText(" ");
displayEntered.setText(displayArray);
}
}
}};
Your real problem is that you are re-using sb without clearing it.
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();
}
private void addCustomerActionPerformed( ActionEvent e )
{
String Query;
Query = "INSERT INTO Membership VALUES"+ "(' " +memberID_a.getText() + " ' , ' " +memberName_a.getText() + " ' , ' " + icNo_a.getText() + " ', ' " + gender_a.getText() +" ' , '" + birthday_a.getText() +" ' , ' " + telephoneNo_a.getText() + " ',' " + mobileNo_a.getText() + " ' , ' " + email_a.getText() + " ' , ' " + address_a.getText() + " ' , " + postalCode_a.getText() + " ,' " + state_a.getText() + " ' , '" + country_a.getText() + " ' , " + memberPoint_a.getText() + ");";
try {
stmtInsert = conn.createStatement();
stmtInsert.executeUpdate(Query);
} catch(Exception ex){
JOptionPane.showMessageDialog(null,"ERROR"+ex.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
}
}
I am getting the error of
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
Anyone help me with this problem ? thanks
This will work
Query ="INSERT INTO Membership VALUES ( " +memberID_a.getText() + " , " +memberName_a.getText() + " , " + icNo_a.getText() + " , " + gender_a.getText() +" ," + birthday_a.getText() +"," + telephoneNo_a.getText() + " , " + mobileNo_a.getText() + " , " + email_a.getText() + " , " + address_a.getText() + " , " + postalCode_a.getText() + ", " + state_a.getText() + " ," + country_a.getText() + "," + memberPoint_a.getText() + ")";