Debug proving something isn't null but issue still occurs [Minecraft] - java

I am trying to make my plugin monitor kills and hp of a player but I am currently getting issues with both health and kills with the same error.
I have even tried using null selection to check if it is null and not use it but that wouldn't work as I need the information to show.
I basically need to set the players hp and name as the scoreboard and the kills as the score. (Thank you in advance).
This sets the players kills when joining:
#EventHandler
public void onPlayerLogin(PlayerJoinEvent e) {
String player = e.getPlayer().getName();
if(!PlayerHandler.GPlayed.containsKey(player)){
PlayerHandler.GPlayed.put(player, 0);
}
if(!PlayerHandler.kills.containsKey(player)){
PlayerHandler.kills.put(player, 0);
}
if(!PlayerHandler.HRound.containsKey(player)){
PlayerHandler.HRound.put(player, 0);
}
}
And here is a debug I tried creating but the same error still shoots with the relevant checks all being correct.
#SuppressWarnings("deprecation")
public void run(String arena){
for(String key : Handler.playerMap.keySet()){
if (Handler.playerMap.get(key).contains(arena)){
Player pt = Bukkit.getPlayer("Nubzz");
String p = pt.getDisplayName();
Player nubzz = Bukkit.getPlayer("Nubzz");
nubzz.sendMessage(key);
nubzz.sendMessage(pt + "");
nubzz.sendMessage(p);
ScoreboardManager manager = Bukkit.getScoreboardManager();
Scoreboard board = manager.getNewScoreboard();
Objective objective = board.registerNewObjective("test", "dummy");
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
objective.setDisplayName(ChatColor.AQUA + "Wave: " );
Score score = objective.getScore(ChatColor.GREEN + "" + pt.getHealth() + ChatColor.WHITE + p + ChatColor.AQUA);
int kills = PlayerHandler.kills.get(p);
score.setScore(kills);
int pcheck = 0;
This shows the debug working and showing the player has kills (Maybe I'm checking the wrong variables values):
https://gyazo.com/35a83b11a1fb384789a15ae54116248d

Related

Need help in minecraft bukkit java development with kit command

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!

Not opening inventory when right clicking

I've been trying to create a custom inventory and everything seems fine but in-game when I try to right-click the item that opens the inventory, the inventory doesn't open.
Inventory playerInfoInv = plugin.getServer().createInventory(null, 27, ChatColor.GOLD + "Player Info");
p.openInventory(playerInfoInv);
}
#EventHandler
public void onInteract(PlayerInteractEvent e) {
Player p = e.getPlayer();
Material getItemInHand = e.getItem().getType();
Action a = e.getAction();
if (getItemInHand.equals(SKULL_ITEM)) {
if (a.equals(Action.LEFT_CLICK_AIR))
playerInfoInventory(p);
}
}
This is the skull item meta if it might impact this:
//Player skull
ItemStack pSkull = new ItemStack(SKULL_ITEM,1,(short) SkullType.PLAYER.ordinal());
SkullMeta pMeta = (SkullMeta) pSkull.getItemMeta();
pMeta.setOwner(p.getName());
pMeta.setDisplayName(ChatColor.BLUE + "Player Info");
ArrayList<String> pSkullLore = new ArrayList<String>();
pSkullLore.add(ChatColor.WHITE + "Show Player Stats");
pMeta.setLore(pSkullLore);
pMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
pSkull.setItemMeta(pMeta);
p.getInventory().setItem(0, pSkull);
At first: e.getItem() can be null. So maybe you could get an NullPointer.
The second: ItemStack#getType() returns Material. And you are checking for SKULL_ITEM not Material.SKULL_ITEM (same mistake you made at initializing your variable pSkull).
The Third: Check if your Listener is Registered.

What's making the object field automatically change?

I'm making a simple Player/Session system but I just found a logic error even that it seems to me that everything is in order.
Let me describe my idea, I'm still learning how OOP works, that's why I'm practicing in this project :
First of all I created two classes :
Class Players
Class Session
In the Session's class I have a method named joinSession(Session s);
This method will make the player's object join the session like so :
Session s1 = new Session();
Player p1 = new Player(name : "Jack");
p1.joinSession(s1);
The problem is that in the Session attributes I have a :
public Player firstPlayerToJoin;
public Player lastPlayerToJoin;
Whenever I make a player join a session everything seems to be fine, Jack is firstPlayerToJoin and lastPlayerToJoin. But the real probleem is when another player decides to join for example :
Player p2 = new Player("Rose");
p2.joinSession(s1);
Rose will once again be firstPlayerToJoin and lastPlayerToJoin instead of only being the lastPlayerToJoin.
Here's my code :
First Player class
private static int id;
private Session session;
boolean isOnSession = false;
public static String name;
public static void say(String message){
System.out.println(name + " says " + message);
}
// Player join session
public void joinSession(Session s){
this.session = s;
System.out.println(name + " joined the session : " + this.session.sessionName );
System.out.println("Players ONLINE = " + s.playersOnline);
if( s.playersOnline == 0){
s.firstPlayerToJoin = this;
s.lastPlayerToJoin = this;
} else {
s.lastPlayerToJoin = this;}
s.playersOnline++;
}
public void quitSession(){
this.session = null;
isOnSession = false;
System.out.println(name + " left his session.");
}
Player(String name){
id = id++;
this.name = name;
}
public static void showPlayerInfo(Player n){
System.out.println("========== Player INFO ==========");
System.out.println("ID : " + id + "\nName : " + name );
}
}
Here's Session class :
public class Session {
int id = 0;
int maxConnected = 10;
public int playersOnline = 0;
String[] playersConnected = new String[maxConnected];
public String sessionName;
public Player firstPlayerToJoin;
public Player lastPlayerToJoin;
Session(){
this.id=id++;
this.sessionName = "SESSION"+id;
}
public void sessionInfo(){
System.out.println("======== Session INFO ========");
System.out.println("Session name : " + sessionName);
System.out.println("Players online : " + playersOnline);
System.out.println("First player to join : " + firstPlayerToJoin.name);
System.out.println("Last player to join : " + lastPlayerToJoin.name);
System.out.println("==============================");
}
int getPlayersOnline(){
return this.playersOnline;
}
}
And finally the main class and method :
public class Main {
public static void main(String[] args) {
Player p1 = new Player("Omar");
Session s1 = new Session();
p1.joinSession(s1);
s1.sessionInfo();
Player p2 = new Player("Rick");
p2.joinSession(s1);
s1.sessionInfo();
}
}
If there's any question or confusion about the idea, let me know.
Actual output :
Omar joined the session : SESSION0
Players ONLINE = 0
======== Session INFO ========
Session name : SESSION0
Players online : 1
First player to join : Omar
Last player to join : Omar
==============================
Rick joined the session : SESSION0
Players ONLINE = 1
======== Session INFO ========
Session name : SESSION0
Players online : 2
First player to join : Rick
Last player to join : Rick
==============================
In the line just before the last one we can see : First player to join : Rick
Player's object p1 overrides the attribute even if there's a condition that's not true.
I am going to elaborate on RealSkeptic's comment (which I did not figure out until he said it).
You have your name field as static. Currently, if you were to write (p1 == p2) you would get false, because they are indeed different objects. By making this a static variable, you are setting it for your entire class (Static variables are called class variables). What you intended to do is localize your variable so that your individual players would have their own names.
Therefore:
public static String name;
should be:
public String name;
Your IDE is probably telling you that you are accessing name in an incorrect way right now. When accessing static variables or methods, you access them through the class themselves rather than objects of that class.
e.g.
Player.NAME
rather than
Player p1 = new Player("tom");
p1.NAME;
because, as mentioned, they are for the class themselves rather than local object instantiations of said class. Here is some further reading if you would like:

I KEEP GETTING ERROR_WRONG_LABEL on Brother Printer QL-710W

I have been trying to get my android code to print to a new Brother Printer but
I keep getting ERROR_WRONG_LABEL.
I also get the information:
D/Brother Print SDK: no such enum object for the id: -1
This is my code:
public void printLabel() {
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
try {
myPrinterInfo.printerModel = PrinterInfo.Model.QL_710W;
myPrinterInfo.ipAddress = "12.1.3.45";//not real ip
myPrinterInfo.macAddress = "";
myPrinterInfo.port = PrinterInfo.Port.NET;
myPrinterInfo.paperSize = PrinterInfo.PaperSize.A7;
myPrinterInfo.printMode=PrinterInfo.PrintMode.FIT_TO_PAGE;
myPrinterInfo.numberOfCopies = 1;
LabelInfo mLabelInfo = new LabelInfo();
mLabelInfo.labelNameIndex = 5;
mLabelInfo.isAutoCut = true;
mLabelInfo.isEndCut = true;
mLabelInfo.isHalfCut = false;
mLabelInfo.isSpecialTape = false;
myPrinter.setPrinterInfo(myPrinterInfo);
myPrinter.setLabelInfo(mLabelInfo);
//File downloadFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("HEYYYY", "startCommunication = " + myPrinter.startCommunication());
Bitmap map = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_overflow);
PrinterStatus printerStatus = myPrinter.printImage(map);
Log.i("HEYYYY", "errorCode-11 = " + printerStatus.errorCode);
Log.i("HEYYYY", "labelWidth = " + myPrinter.getLabelParam().labelWidth);
Log.i("HEYYYY", "paperWidth = " + myPrinter.getLabelParam().paperWidth);
Log.i("HEYYYY", "labelNameIndex " + mLabelInfo.labelNameIndex);
Log.i("HEYYYY", "printers " + myPrinter.getNetPrinters("QL-710W"));
Log.i("Label-id", myPrinter.getPrinterStatus().labelId + "");
myPrinter.endCommunication();
} catch(Exception e){
e.printStackTrace();
}
}
Whenever I put the mac address which I got from the printer page, the error code changes to
ERROR_NOT_MATCH_ADDRESS.
But without it(setting it to an empty string or commenting it out), it changes to
ERROR_WRONG_LABEL.
What is wrong with this code, please?
UPDATE:
I inserted the correct mac id and now the error code is
ERROR_WRONG_LABEL
what do I do?
After reading through the manual that came with it, I discovered that the ERROR_WRONG_LABEL code occurs due to wrong labelNameIndex or wrong paperSize.
I set the labelNameIndex value to 15 and, voila it worked.
I feel anyone facing this problems should try out various values for the labelNameIndex.
Thanks.

SwingWorker still causing non-responsive UI during computation

I am writing a UI that starts a SwingWorker to call some outside library functions, specifically from the neuroph library, to simulate neural networks. In the SwingWorker I either generate a population of Genomes or I run some population through a genetic algorithm to find the best Genomes.
The worker generates an initial population and returns fast enough that I can't tell if the calls to SwingWorker.process complete before the SwingWorker calls SwingWorker.done. Though running the population through the genetic algorithm causes the UI to freeze until it has completed (currently not allowing me to test any further). No .process messages are sent to the UI when the genetic algorithm logic is used, until it completes.
I also noticed that the library writes to the standard output for each LearningEvent generated by the instantiated neural network. So when the SwingWorker is processing the population of neural networks "tons" (3 lines per network learning and testing) of output is generated. Could this be causing the backup of .process calls back to the UI?
Is there a way to force a SwingWorker to wait until all of its .process messages have been sent and received by the UI?
Here is a code sample of the SwingWorker
public class MLPEnvironment extends SwingWorker<Boolean, String>
{
int gensRan = 0;
boolean usingGA;
DataSet envData;
MainView mainView;
LinkedList<Genome> population;
EnvironmentParameters envParms;
public MLPEnvironment(MainView inView, EnvironmentParameters inParms, LinkedList<Genome> inPop, DataSet inData)
{
envData = inData;
mainView = inView;
envParms = inParms;
population = inPop;
usingGA = envParms.evolveAtleastOneParameter();
}
// Main logic of worker
#Override
protected Boolean doInBackground() throws Exception
{
Boolean retVal = Boolean.TRUE;
// Generate a initial population if this flag is set
if(envParms.m_bGenerateInitPop)
{
newStatus("> Generating initial population...");
generateInitialPopulation();
}
// If we are not just generating a population, but running the GA
if(!envParms.m_bOnlyGenInitPop)
{
newStatus("> Running evolution on population...");
startBigBang();
newStatus("- Number of generations ran: " + gensRan);
}
// Otherwise just push the initial population to the UI for the user to see
else
{
newStatus("> Pushing population to UI...");
newStatus("ClearTable");
for(int i = 0; i < population.size(); i++)
{
Genome curGen = population.get(i);
String layerWidths = "";
for(int j = 0; j < curGen.getLayerWidths().size(); j++)
{
layerWidths += curGen.getLayerWidths().get(j).toString();
if(j != curGen.getLayerWidths().size()-1)
layerWidths += "-";
}
newStatus("NewRow" + GenomeFitnessResults.getResultsCSV(curGen) + curGen.getTFType() + "," + curGen.getLayerWidths().size() + "," + layerWidths + ",");
}
newStatus("- Done displaying initial population");
}
newStatus("Environment worker thread finished");
return retVal;
}
// Generate the initial population
private void generateInitialPopulation()
{
newStatus(" Initial population size: " + envParms.m_iInitPopSize);
newStatus(" DataInSize: " + envData.getInputSize() + " DataOutSize: " + envData.getOutputSize());
newStatus(" Trans: " + envParms.m_bEvolveTransferFunction + " Count: " + envParms.m_bEvolveHiddenLayerCount + " Widths: " + envParms.m_bEvolveHiddenLayerWidth);
for(int i = 0; i < envParms.m_iInitPopSize; i++)
{
population.add(Genome.getGenomeFromParms(envParms));
}
newStatus("- Finished generating initial population");
}
// The start of the GA, the beininng of the networks "universe"
private void startBigBang()
{
newStatus(" Using genetic algorithm: " + usingGA);
newStatus(" Evaluating initial population...");
population = Genome.evaluate(population, envData, envParms);
newStatus(" Done evaluating initial population");
if(usingGA)
{
newStatus(" > Starting genetic algorithm...");
for(int i = 0; i < envParms.m_iNumGenerations; i++)
{
gensRan++;
newStatus(" Generation: " + gensRan);
population = Genome.select(population, envParms);
population = Genome.crossOver(population, envParms);
population = Genome.mutate(population, envParms);
population = Genome.evaluate(population, envData, envParms);
}
newStatus(" - Genetic algorithm terminated");
}
newStatus("- Done running algorithm");
}
// Clean-up and closure after main process
#Override
protected void done()
{
try
{
final Boolean retVal = get();
mainView.environmentRunComplete(retVal, population);
}
catch (InterruptedException ex)
{
// Not sure who I can tell...
System.out.println("DC: InterruptedException");
mainView.environmentRunComplete(Boolean.FALSE, null);
}
catch (ExecutionException ex)
{
// Not sure who I can tell...
System.out.println("DC: ExecutionException");
mainView.environmentRunComplete(Boolean.FALSE, null);
}
}
// These are used to write updates to the main view
private void newStatus(String arg)
{
publish(arg);
}
#Override
protected void process(List<String> list)
{
list.stream().forEach((line) -> { mainView.newStatusLine(line); });
}
}
EDIT: So another way to put it.
I understand that
publish("a");
publish("b", "c");
publish("d", "e", "f");
Might actually result in
process("a", "b", "c", "d", "e", "f")
being called. Is there any defined interval when the process "batches" go to the UI? When I start the swing worker with a button click the UI becomes unresponsive, but the library prints system output lines, then once all the swingworker computation is done I then see all of the calls the newStatus in the UI.
So I know that the worker is doing some intense work, but why are all calls to newStatus over the few seconds it takes to do its work batched into a single publish after all work is complete? Shouldn't some publish calls get sent to the UI prior and before an intensive task is performed?
If anything, shouldn't the UI remain responsive because none of the messages are being shown as the swing worker is working?

Categories