I have made plugin that have 2 kits first with name Iron and the other with the name DProtect
so i want them to give items and i made everything and i made a cool down the problem is when i type /kit Iron or /kit DProtect it doesn't work i tried to do a lot of things and doesn't work this is the code can i have some help ?
package Rivals.iSryMan.Kits.commands;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import Rivals.iSryMan.Kits.Main;
public class Kit implements CommandExecutor{
private HashMap<UUID,Long> ironcooldown = new HashMap<UUID,Long>();
private int ironcooldowntime = 300;
private HashMap<UUID,Long> DProtectcooldown = new HashMap<UUID,Long>();
private int DProtectcooldowntime = 5259487;
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(sender instanceof Player) {
Player p = (Player)sender;
if(args.length == 1) {
//Kit Iron
if(args[0].equals("Iron")) {
if(ironcooldown.containsKey(p.getUniqueId())) {
long ironsecondsleft = ( (ironcooldown.get(p.getUniqueId())/ 1000) + ironcooldowntime) - (System.currentTimeMillis() / 1000);
if(ironsecondsleft > 0) {
p.sendMessage(Main.Color(Main.prefix + "You must wait " + ironsecondsleft + " before you take that kit again!"));
}else if(ironsecondsleft == 0) {
final ItemStack ironhelmet = new ItemStack(Material.IRON_HELMET);
final ItemStack ironchestplate = new ItemStack(Material.IRON_CHESTPLATE);
final ItemStack ironleggings = new ItemStack(Material.IRON_LEGGINGS);
final ItemStack ironboots = new ItemStack(Material.IRON_BOOTS);
p.getInventory().addItem(ironhelmet);
p.getInventory().addItem(ironchestplate);
p.getInventory().addItem(ironleggings);
p.getInventory().addItem(ironboots);
p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));
}
}
//Kit Iron
//Kit DProtect
} else if (args[0].equals("DProtect")) {
if(DProtectcooldown.containsKey(p.getUniqueId())) {
long DProtectsecondsleft = ( (DProtectcooldown.get(p.getUniqueId()) / 1000) + DProtectcooldowntime) - (System.currentTimeMillis() / 1000);
if(DProtectsecondsleft > 0) {
p.sendMessage(Main.Color(Main.prefix + "You must wait " + DProtectsecondsleft + " before you take that kit again!"));
}else if(DProtectcooldowntime == 0) {
final ItemStack dphelmet = new ItemStack(Material.IRON_HELMET);
final ItemMeta dphelmetmeta = dphelmet.getItemMeta();
final ItemStack dpchestplate = new ItemStack(Material.IRON_CHESTPLATE);
final ItemMeta dpchestplatemetaa = dphelmet.getItemMeta();
final ItemStack dpleggings = new ItemStack(Material.IRON_LEGGINGS);
final ItemMeta dpleggingsmeta = dphelmet.getItemMeta();
final ItemStack dpboots = new ItemStack(Material.IRON_BOOTS);
final ItemMeta dpbootsmeta = dphelmet.getItemMeta();
ArrayList<String> dplore = new ArrayList<String>();
dplore.add(Main.Color("&bAuthentic Protection 4 Armor"));
//Set Meta
dphelmet.setItemMeta(dphelmetmeta);
dpchestplate.setItemMeta(dpchestplatemetaa);
dpleggings.setItemMeta(dpleggingsmeta);
dpboots.setItemMeta(dpbootsmeta);
//Set Meta
//Set Lore
dphelmetmeta.setLore(dplore);
dpchestplatemetaa.setLore(dplore);
dpleggingsmeta.setLore(dplore);
dpbootsmeta.setLore(dplore);
//Set Lore
//Adding Kit
p.getInventory().addItem(dphelmet);
p.getInventory().addItem(dpchestplate);
p.getInventory().addItem(dpleggings);
p.getInventory().addItem(dpboots);
//Adding Kit
p.sendMessage(Main.Color(Main.prefix + " You've got your kit, Enjoy!"));
}
}
//Kit DProtect
}
return true;
}
}
return false;
}
}
Have you made sure:
Your command is registered in onEnable() and plugin.yml?
You type specifically 'Iron' with a capital I? You should allow for different cases, using equalsIgnoreCase()
This is probably the issue. Your HashMap does not contain the UUID of the CommandExecutor at first, therefore it never gets passed the ironcooldown.containsKey(p.getUniqueId()). I would recommend checking if they are in it. If they are, check if the time is 0, otherwise add them after the code has been executed.
Let me know if this works.
Also, you should fix the indentation of your code - it confused me at first and it may confuse you in the future. This is not a big deal, however.
Although Slinthn answered your questions, I thought I'd add a bit more of an explanation.
You declare a private HashMap for both kits cooldown's: ironcooldown and DProtectcooldown.
You check within your onCommand if the player executing the command is in that HashMap in your condition if(ironcooldown.containsKey(p.getUniqueId())), however, that condition will never be true because the player's UUID is never added to the HashMap.
It looks to me like you want to do something like the following (half pseudo-code)
if(!(sender instanceof Player))
return true;
if(args.length == 0)
return true;
Player p = (Player) sender;
if(args[0].equalsIgnoreCase("iron")){
if(ironcooldown.containsKey(p.getUniqueId())){
//Do check if they are still on cooldown
//... if so, return here
}
ironcooldown.put(p.getUniqueId(), System.currentTimeMillis());
givePlayerKit(Kits.IRON, p); //made up function that takes Enum & Player
}
//etc
It seems that you haven't added the player to the HashMap so it will return false so you might want to make your HashMaps public and static and inside your PlayerJoinEvent (if you have one) add
Kit.ironcooldown.put(p.getUniqueId(), 0);
or if you don't have a PlayerJoinEvent and/or you don't want to do that, you can put before your args check
if (!ironcooldown.containsKey(p.getUniqueId()) {
ironcooldown.put(p.getUniqueId(), 0);
}
Do the same for Dprotectcooldown.
Hope this helped!
Related
I few days ago I started messing around with Javas, wanting to create a small tool for League of Legends. Now I encountered a very frustrating error.
indexOf stopped working, but I just can't figure out why. Every time I check the list "players" for the position of the entered name (l1v3 in this case) it just responds with -1. So item not found. Even though is shows up when printing the "players" list.
What did I do wrong? I'm new to coding so thanks for the help in advance!
This is the output I get:
Name: Abanke
Summoner ID: QvpMxe-XUEfD2WQujoDzHg9q4_co-7A1B6QC4W51qh8r1B0
[kus olan kumru, Abanke, Al Muqtadir, Lilipp, Solalicious, Young BuII, Nimecchii, imapz, FSL Nubels, Ulanbator Raimi]
Enemies[Young BuII, Nimecchii, imapz, FSL Nubels, Ulanbator Raimi]
-1
Code:
package leaguetimer;
import java.util.ArrayList;
import java.util.List;
import net.rithms.riot.api.ApiConfig;
import net.rithms.riot.api.RiotApi;
import net.rithms.riot.api.RiotApiException;
import net.rithms.riot.api.endpoints.summoner.dto.Summoner;
import net.rithms.riot.constant.Platform;
import net.rithms.riot.api.endpoints.spectator.dto.CurrentGameInfo;
public class LeagueTimer {
/**
* #param args the command line arguments
* #throws net.rithms.riot.api.RiotApiException
*/
public static void main(String[] args) throws RiotApiException {
// TODO code application logic here
ApiConfig config = new ApiConfig().setKey("RGAPI-9aa36868-192b-481b-b9c7-a04facf84ce1");
RiotApi api = new RiotApi(config);
Summoner summoner = api.getSummonerByName(Platform.EUW, "Abanke");
System.out.println("Name: " + summoner.getName());
System.out.println("Summoner ID: " + summoner.getId());
CurrentGameInfo match = api.getActiveGameBySummoner(Platform.EUW, summoner.getId());
List players = new ArrayList();
players = match.getParticipants();
System.out.println(players);
int check = players.indexOf(summoner.getName());
if (check < 5) {
List subList = match.getParticipants().subList(5, 10);
System.out.println("Enemies" + subList);
System.out.println(check);
}
else {
List subList = match.getParticipants().subList(0, 4);
System.out.println("Enemies" + subList);
}
}
}
Main Class
package main;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.Test;
import lib.Die;
import lib.Name;
import lib.PairOfDice;
import lib.Player;
public class PlayerAppTest {
/* Please note - when we come to mark the solution to this unit test we will change the input
* data set for the players added to the list to ensure the solution works dynamically based
* upon any given data set and is not hardcoded in any way.
*/
#Test
public void testExecute() {
ArrayList<Player> players = new ArrayList<>();
players.add(new Player(new Name("Joe", "Bloggs"), new PairOfDice()));
players.add(new Player(new Name("Fred", "Jones"), new Die()));
players.add(new Player(new Name("Nila", "Singh"), new PairOfDice(new Die(5), new Die(5))));
String result = PlayerApp.execute(players, "Cassie Downturn");
String expectedResult = "cassie, DOWNTURN\nnila, SINGH\n";
assertEquals("The string returned should match the expected result (run 1)", expectedResult, result);
/* Test with a second set of input data */
ArrayList<Player> players2 = new ArrayList<>();
players2.add(new Player(new Name("David", "Blunt"), new PairOfDice()));
players2.add(new Player(new Name("Tim", "Jonas"), new Die(5)));
players2.add(new Player(new Name("Remi", "Patel"), new Die()));
String result2 = PlayerApp.execute(players2, "Cassie Downturn");
String expectedResult2 = "cassie, DOWNTURN\ntim, JONAS\nremi, PATEL\n";
assertEquals("The string returned should match the expected result (run 2)", expectedResult2, result2);
}
}
Hello, this is the JUnit test which I have to pass, below is the code that I have written in my main package;
JUnit Test Class
package main;
import java.util.ArrayList;
import lib.Player;
public class PlayerApp {
public static String execute(ArrayList<Player> players, String fullName) {
players.get(0).setFullPlayerName(fullName);
fullName = "";
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
}
System.out.println(fullName);
}
return fullName;
}
}
This is the code in my main package, I am trying to print out the names which contain a char "a" in the first name, the first name should be lowercase and the family name should be uppercase. It should print out
cassie, DOWNTURN
nila, SINGH which is the names with a new line between them, however, when i print it, it prints the following;
cassie, DOWNTURN
cassie, DOWNTURN
nila, SINGH
I am confused as to why cassie, DOWNTURN has been printed twice as i cannot find the error in my code, any help would be greatly appreciated, thank you.
You will print it even if the if doesn't match as it's outside the if-statement. Move it inside instead.
for (int i = 0; i <players.size(); i ++) {
if (players.get(i).getName().getFirstName().toLowerCase().contains("a") || players.get(i).getName().getFamilyName().toUpperCase().contains("a")) {
fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullName);
}
}
Your print statement is not conditional and will always execute, move it inside the if. You're printing twice as your are not changing the value in fullName if the if condition does not evaluate as true. Further your family name comparison will always be false as you're comparing upper and lower case.
Your code can also be tided up and made easier to read:
for(Player player : players){
if(player.getName().getFirstName()).toLowerCase().contains("a")||player.getName().getFamilyName().toUpperCase.contains("A"))){
String fullName = players.get(i).getName().getFirstName().toLowerCase() + ", " + players.get(i).getName().getFamilyName().toUpperCase() + "\n";
System.out.println(fullname);
}
}
I want to create a custom Skeleton that has a name, more health and holds other custom items.
I can add a name and setHealth(), but I can't setMaxHealth() and also setting items and armor just won't work.
Thanks for helping, here is my code:
Player p = (Player) sender;
WorldServer world = ((CraftWorld)p.getWorld()).getHandle();
Location loc = p.getLocation();
if (args.length > 0) {
if (args[0].equalsIgnoreCase("define")) {
//get worldedit selection
if (getWorldEdit().getSelection(p) == null) {
p.sendMessage(title + "Please select a region with WorldEdit");
return false;
}
s = getWorldEdit().getSelection(p);
Location min = s.getMinimumPoint();
Location max = s.getMaximumPoint();
//boss mob creation
EntitySkeleton boss = new EntitySkeleton(world);
boss.setHealth(400);
boss.setCustomName("§4§lDAFT BOSS");
boss.setCustomNameVisible(true);
ItemStack weapon = new ItemStack(Material.DIAMOND_SWORD);
weapon.setDurability((short) 0);
weapon.addEnchantment(Enchantment.DAMAGE_ALL, 5);
weapon.addUnsafeEnchantment(Enchantment.KNOCKBACK, 2);
boss.setLocation(max);
world.addEntity(boss);
}
That can be obtained using the Attributable interface, as said in this thread from Spigot.
Example:
For 1.9 and over:
Entity boss;
Attributable bossAttributable = (Attributable) boss;
AttributeInstance ai = bossAttributable.getAttribute(Attribute.GENERIC_MAX_HEALTH);
ai.setValue(400.0);
For 1.8.8 and lower, this must be done another way:
Entity boss;
Damageable bossDamageable = (Damageable) boss;
bossDamageable.setMaxHealth(400.0);
I am trying to read a file of string int and boolean values into an array list as object blocks. The string values go into the array list just fine, its the boolean values I'm having trouble with. Every time I encounter the variable 'active'there is a mismatch exception. Please help! The text file for if the block is a wizard goes in this order
name (string)
location (string)
active (boolean) ... the one I'm having issues with
skill level (int)
friendliness (int)
I included the driver class as well as the Witch class which contains the
variable 'active' originally.
Driver class that adds objects to the array list based on what the scanner
reads from the file
package project2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class Project2 {
public static void main(String[] args) {
Scanner inputFileScanner1 = null;
//file name
String listFile = "list.txt";
// Check to see if file exists
try {
inputFileScanner1 = new Scanner(new File(listFile));
} catch (FileNotFoundException e) {
System.out.println("Error opening file.");
System.exit(1);
}
//create Individuals arraylist and Location arraylist
ArrayList < Individual > Individual = new ArrayList < > ();
ArrayList < String > Location = new ArrayList < > ();
//declare variables to read file contents into the arraylist
String wizName, witchName, individualName, location, position,
profession = null, line = null;
int wizLevel, witchSkillLevel, friendliness;
boolean active;
//while there is a next line, if the line equals Wizard, the next four lines
// are wizard name, location, position and level
while (inputFileScanner1.hasNext()) {
line = inputFileScanner1.nextLine();
if (line.trim().equals("Wizard")) {
wizName = inputFileScanner1.nextLine().trim();
location = inputFileScanner1.nextLine().trim();
position = inputFileScanner1.nextLine().trim();
wizLevel = inputFileScanner1.nextInt();
//create wizard object
Individual wizard = new Wizard(wizName, location, position, profession, wizLevel);
//fill arraylist with wizard objects
Individual.add(wizard);
Location.add(location);
} //if the next line is Witch, the next five lines are
// witch name, location, yes/no active, skill level, and friendliness
//in that order
else if (line.trim().equals("Witch")) {
witchName = inputFileScanner1.nextLine().trim();
location = inputFileScanner1.nextLine().trim();
active = inputFileScanner1.nextBoolean();
witchSkillLevel = inputFileScanner1.nextInt();
friendliness = inputFileScanner1.nextInt();
//create witch object
Individual witch = new Witch(witchName, location, profession, witchSkillLevel, friendliness, active);
//fill the arraylist with witch objects
Individual.add(witch);
Location.add(location);
} else {
profession = line.trim();
individualName = inputFileScanner1.nextLine().trim();
location = inputFileScanner1.nextLine().trim();
Individual i = new Individual(profession, individualName, location);
Individual.add(i);
Location.add(location);
}
java.util.Collections.sort(Individual);
java.util.Collections.sort(Location);
}
System.out.println("List of friends and possible allies: " + Location);
inputFileScanner1.close();
}
}
//Witch class which holds values that are in the text file. active is the boolean value Im having trouble with
package project2;
public class Witch extends Individual implements Magical {
private int skill;
private int friendly;
//Constructor with witch parameters
public Witch(String name, String location, String profession,
int skill, int friendly, boolean active) {
}
//default constructor
public Witch() {
this("", "", "", 0, 0, false);
}
//overridden abstract method from magical interface
#Override
public void assess() {
System.out.print(this.friendly + " " + this.skill + " " + super.toString());
}
}
<!-- end snippet -->
Text file :
enter image description here
When you pull in your boolean variable do something like this.
if(inputFileScanner1.nextLine().trim().equals("yes"))
{
active = true;
}
else
{
active = false;
}
Okay, the problem is that the file contains the strings yes and no, that are not directly parsable as booleans (should be true or false).
If you can change the original data file somehow, I would suggest to use the two true and false keywords, otherwise, the #Sendrick Jefferson solution will do the job (at your own risk: every typo, as for instance "ye", will be translated into false).
I am using cardme library to deal with vcards. Following is my code
package vcardtest;
import java.io.*;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.cardme.engine.VCardEngine;
import net.sourceforge.cardme.vcard.VCard;
import net.sourceforge.cardme.vcard.features.EmailFeature;
import net.sourceforge.cardme.vcard.features.NameFeature;
import net.sourceforge.cardme.vcard.features.NicknameFeature;
import net.sourceforge.cardme.vcard.features.TelephoneFeature;
import net.sourceforge.cardme.vcard.types.parameters.TelephoneParameterType;
public class VCardTest
{
public static void main(String[] args)
{
File vcardFile = new File("C:/Users/yohan/Contacts/Yohan Weerasinghe.vcf");
VCardEngine vcardEngine = new VCardEngine();
try
{
VCard vcard = vcardEngine.parse(vcardFile);
String name = vcard.getName().getGivenName();
EmailFeature email = vcard.getEmails().next();
String sEmail = email.getEmail();
NicknameFeature nickName = vcard.getNicknames();
Iterator<String> nicknames = nickName.getNicknames();
String sNickName = nicknames.next();
Iterator<TelephoneFeature> telephoneNumbers = vcard.getTelephoneNumbers();
TelephoneFeature next = telephoneNumbers.next();
String telephone = "";
while(vcard.getTelephoneNumbers().hasNext())
{
TelephoneFeature next1 = vcard.getTelephoneNumbers().next();
telephone = next1.getTelephone();
System.out.println(telephone);
}
Iterator<TelephoneParameterType> telephoneParameterTypes = next.getTelephoneParameterTypes();
TelephoneParameterType next1 = telephoneParameterTypes.next();
String type = next1.getType();
TelephoneParameterType next2 = telephoneParameterTypes.next();
String type2 = next2.getType();
System.out.println( name );
System.out.println(sEmail);
System.out.println(sNickName);
System.out.println(type);
System.out.println(type2);
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
However, there is no method called getNumber() or something. How can I get the mobile numbers and land numbers? Please help!
NOTE: I UPDATED THE CODE. In there, you can see I managed to get the phone number. But, this returns only the HOME phone and not anything else. Even the loop is not stopping. Please help!
I can see
TelephoneFeature.getTelephone()
I'd also suggest taking a look at
TelephoneFeature.getTelephoneParameterTypes()
to see the types
UPDATE
Be careful with the iterators
Each call to vcard.getTelephoneNumbers() is creating a new Iterator, which means you could end up in an infinite loop.
Iterator<TelephoneFeature> itNumbers = vcard.getTelephoneNumbers();
while (itNumbers.hasNext()) {
TelephoneFeature next1 = itNumbers.next();
String telephone = next1.getTelephone();
System.out.println(telephone);
System.out.println("types = " + next1.getExtendedTelephoneParameterSize());
Iterator<XTelephoneParameterType> itTypes = next1.getExtendedTelephoneParameterTypes();
while (itTypes.hasNext()) {
XTelephoneParameterType next = itTypes.next();
System.out.println(" - " + next.getType() + " / " + next.getDescription());
}
}
I stand corrected, the problem (isn't a bug) it's with the tester, not the API :P
If you add
Iterator<TelephoneParameterType> itNTypes = next1.getTelephoneParameterTypes();
while (itNTypes .hasNext()) {
TelephoneParameterType next = itNTypes .next();
System.out.println(" - " + next.getType() + " / " + next.getDescription());
}
to the previous loop, you should get what you're looking for