Import Boolean from another Class - java

I have a DataHolders class.
It contains:
public static boolean hit;
In my other class theres:
public void onHit(ProjectileHitEvent event) {
if (event.getHitEntity() != null || event.getHitBlock() != null) {
DataHolders.hit = true;
}
}
ProjectileHitEvent gets triggered when a Player hits something with a Projectile (Arrow)
In my last class:
public void onLaunch(ProjectileLaunchEvent event) {
while (!DataHolders.hit) {
//..............
}
}
ProjectileLaunchEvent gets triggered when a Player launches the Projectile (Arrow)
I want to do something while the Projectile (Arrow) is in the air (ProjectileLaunchEvent triggered but ProjectileHitEvent not).
But when the Arrow hits something (ProjectileHitEvent gets triggered and boolean hit becomes true) the loop should stop but the while loop goes on. I've already tested if ProjectileHitEvent really gets triggered, it works but the loop doesn't.

check if DataHolders.hit is true/false.
public void onLaunch(ProjectileLaunchEvent event) {
while (!DataHolders.hit) {
System.out.println(DataHolders.hit);
//..............
}
}
If true
You should focus on setting DataHolders.hit properly
If false
Print the value before/after setting the value
public void onHit(ProjectileHitEvent event) {
if (event.getHitEntity() != null || event.getHitBlock() != null) {
System.out.println(DataHolders.hit);
DataHolders.hit = true;
System.out.println(DataHolders.hit);
}
}
If the latter output is true then there is a problem with the class where public static boolean hit; exists.

Related

How to set/call object and method in condition

How is it possible to set an object and method in a condition? I understand that, if the animal is over 50kg it weighs too much. But how about if an animal is hangry, need Love and feel boring return the method feelingNegative()?
I don't know how to set it. But after an animal sleeps, it is hangry. A thought would be:
Animal {
if (hangry == false && needLove == false && boring == false) {
return feelingNegative();
}
}
still don't know how to set it.
public class Animal {
private boolean needLove;
private boolean hangry;
private boolean boring;
private int kg;
public boolean sleep() {
return hangry = true;
}
public boolean watchTv() {
return needLove = true;
}
public void feelingPositive() {
System.out.println("I feel good");
}
public void feelingNeutral() {
System.out.println("Someting is missing...");
}
public void feelingNegative() {
System.out.println("I need love, food and fun!");
}
public void weight(int kg) {
if(50 < kg) {
System.out.println("You ate way too much");
}else {
System.out.println("You need to eat more");
}
}
}
The methods you are calling don't return anything (they are void). Just remove the return. And use boolean negation (!) instead of == false. Like,
if (!hangry && !needLove && !boring) {
feelingNegative();
}
The Method feelingNegative() doesn't return anything (Void). So you just have to define a method that call feelingNegative() when all the conditions are satisfied.
public void myMethod ()
{
if(!hangry && !needLove && !boring)
feelingNegative();
}

Why is this boolean coming out false even when one of the conditions is true?

So I have this simple boolean method for checking whether my game has ended. In the main method, I then have a big loop that starts with the statement while (isGameEnd() == false) {...}. This loop never seems to break, even when one, two or all of the conditions in the method becomes true. I don't get it.
public static boolean isGameEnd() {
if (lives == 0 || steps == 0 || isMazeCompleted()) { return true; }
else { return false; }
}
The use of static in the function definition is a red flag to me. If a class is defined with default field values, then those default values will be what is checked rather than the particular implementation of the class:
class Game {
int lives = 3;
int steps = 10;
public boolean isMazeCompleted() {
return false;
}
public void doStuff() {
lives--;
}
public static boolean isGameEnd() {
if (lives == 0 || steps == 0 || isMazeCompleted()) {
return true;
} else {
return false;
}
}
}
public static void main(String[] args){
Game a;
while(!a.isGameEnd()){ // check 'isGameEnd' for the static class
a.doStuff(); // This does *not* update the static class
}
}
Most Java editors will complain about the use of static functions in a non-static context, so will suggest Game.isGameEnd() instead of a.isGameEnd(), which makes it a bit more obvious to the programmer where the error is.

Boolean use for decision making

Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean in the correct way.
public Space fire()
{
System.out.println("Hi");
}
public boolean hitRateAnalysis()
{
if (HitShipPercentage < 50 && Shots!=0)
return true;
else{
return false;
}
}
Your fire() is wrong and will cause a compilation error, you have to return an instance of Space. Either change the return type of the method to void or return an instance of the Space class.
This will call the fire method correctly:
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots != 0){
fire();
return true;
}
return false;
}
Your code has a few errors in it, the fire() method is of type Space which means it's supposed to return a Space. I don't think this is what you want, my guess is fire isn't supposed to return anything in which case it should be void.
public void fire() {
System.out.println("Hi");
}
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots!=0) {
fire();
return true;
}
return false;
}

Java boolean returning true when declared false

I am currently making a plugin from the 1.8 Bukkit API. This question however, has to do with booleans. From the beginning of my class file, I have this declaration of a boolean
public static boolean lockchat = false;
Then I have another boolean in the class file that is used for Bukkit commands:
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args)
This boolean returns true at the end, which I think is making the lockchat boolean return true also. If I return false, I am pretty sure that the command code will not return to the user.
My problem is that in this part of my code:
if(lockchat == true)
{
s.sendMessage("unlocked.")
lockchat = false;
}
else
{
s.sendMessage("locked.");
lockchat = true;
}
The declaration at the beginning does not seem to matter here, because this always sends me the message unlocked.
I have tried to put the declaration inside of the second boolean, but it throws me errors and warnings.
Since the second boolean is returning true, I think that the lockchat boolean is returning too. If I would change it to return false, lockchat would probably return false also, resulting in another problem.
I want to find a way to have the boolean declaration stay false, while having it changed to true/false inside of the second boolean, as shown. How would I do this?
NOTE: This variable is not used anywhere else in my code.
EDIT: I don't think this will make a difference, but I am testing for the label string to be "lockchat", the same as the boolean name. This probably wouldn't change anything, but just giving more information.
FULL CLASS FILE CODE:
package dev.td6.duocraft.commands;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import dev.td6.duocraft.main.Duocraft;
public class DCCommandLockChat implements CommandExecutor, Listener
{
Duocraft plugin;
public DCCommandLockChat(Duocraft instance)
{
plugin = instance;
}
public String colorize(String msg)
{
String coloredMsg = "";
for(int i = 0; i < msg.length(); i++)
{
if(msg.charAt(i) == '&')
coloredMsg += 'ยง';
else
coloredMsg += msg.charAt(i);
}
return coloredMsg;
}
public static boolean lockchat = false;
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args)
{
if(s instanceof Player)
{
Player p = (Player) s;
if(label.equalsIgnoreCase("lockchat"))
{
if(p.hasPermission("duocraft.lockchat"))
{
if(args.length >= 1)
{
if(args.length >= 2)
{
s.sendMessage("Too many arguments. </lockchat [time]>");
}
else
{
if(lockchat == true)
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked.");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
else
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked.");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked.");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
}
}
else
{
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
}
}
else
{
p.sendMessage("no access");
}
}
}
else
{
if(label.equalsIgnoreCase("lockchat"))
{
if(args.length >= 1)
{
if(args.length >= 2)
{
s.sendMessage("Too many args. </lockchat [time]>");
}
else
{
if(lockchat == true)
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked.");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked.");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
else
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
}
}
else
{
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
}
}
}
return true;
}
#EventHandler
public void chatLocked(AsyncPlayerChatEvent e)
{
if(lockchat==false)return;
Player p = e.getPlayer();
if(p.hasPermission("duocraft.lockchat.bypass"))return;
p.sendMessage("chat is locked.");
e.setCancelled(true);
}
}
EDIT: Also public static boolean lockchat = false; Is not being modified in any way by any other class files.
EDIT: I am using Java 7 for this.
Just so you know, in your full source you use the following code:
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
more specifically, you are sending "unlocked" no matter which path the code follows.
Edit: I reformatted your code to reduce some of the duplication. This version fails fast if the CommandSender is a player without permission or the label is not "lockchat". I inferred that the intention is that executing "/lockchat" without an argument should toggle locking immediately, while executing it with an argument should make it toggle for the specified number of seconds and then toggle back. The code below should do this (at least as far as ensuring lockchat always has the intended value, but I haven't tested it.
Also, I don't know if the Runnable will be called on a different thread, but if it is you should synchronize all accesses to the shared lockchat variable. At the very least, making it volatile (as I do below) may prevent some confusion amongst the threads as to its actual value.
public static volatile boolean lockchat = false;
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
// If this is not the 'lockchat' command, then fail fast
if (!label.equalsIgnoreCase("lockchat")) return true;
// If s is a Player then check the player has permission and fail fast
// if not.
if (s instanceof Player) {
Player p = (Player) s;
if (!p.hasPermission("duocraft.lockchat")) {
p.sendMessage("no access");
return true;
}
}
switch (args.length) {
case 0:
lockchat = !lockchat;
s.sendMessage(lockchatStatus());
break;
case 1:
int ticks = Integer.valueOf(args[0]) * 20;
final boolean originalLockChat = lockchat;
lockchat = !originalLockChat;
s.sendMessage(lockchatStatus());
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() {
#Override
public void run() {
lockchat = originalLockChat;
Bukkit.broadcastMessage(lockchatStatus() + ".");
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}, ticks, ticks);
break;
default:
s.sendMessage("Too many arguments. </lockchat [time]>");
break;
}
return true;
}
private String lockchatStatus() {
return lockchat ? "locked" : "unlocked";
}
As stated in Julian's answer, your code is returning unlocked no matter what the value :
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
As per your comment regarding as to why it is not blocking the chat, are you sure you registered your listener? To register your listener, put this line in your onEnable() method in your Main class :
getServer().getPluginManager().registerEvents(new DCCommandLockChat(), this);
Where DCCommandLockChat() is your Listener class and 'this' is your class that extends JavaPlugin.
What this basically does is register your listener for your plugin because otherwise, the server wouldn't pass any events to your listener and so your listener wouldn't know what would be happening on the server.
Also, as for the method itself returning true or false, both values will still run the command. As far as I know, the only time the return value of the onCommand method matters is when you're using aliases in your plugin.yml. If the method returns false, then the server will send the player a message with the aliases. Aside from that, it doesn't really matter.
You should give the boolean (lockchat) the value you want in the constructor of your class.
To answer your question:
I want to find a way to have the boolean declaration stay false, while having it changed to true/false inside of the second boolean, as shown. How would I do this?
At the beginning of the body of whichever statement you want, make a temporary variable to store lockChat's value.
boolean lockChatTemp = lockChat;
Then, use and modify that value within your function. This way, lockChat will keep its value throughout.
Also,
if (lockChat == true)
can be replaced with
if (lockChat) since the statement inside the parentheses evaluates to a boolean, and lockChat is already a boolean.

Return Statements in a Finite State Machine

Could anyone tell me what purpose a return statement in a Finite State Machine's state serves? For example I have this code for a soccer player's state:
public class ChaseBall extends State<FieldPlayer> {
private static ChaseBall instance = new ChaseBall();
private ChaseBall() {
}
//this is a singleton
public static ChaseBall Instance() {
return instance;
}
#Override
public void Enter(FieldPlayer player) {
player.Steering().SeekOn();
}
}
#Override
public void Execute(FieldPlayer player) {
//if the ball is within kicking range the player changes state to KickBall.
if (player.BallWithinKickingRange() && player.isReadyForNextKick()) {
player.GetFSM().ChangeState(KickBall.Instance());
return;
}
//if the player is the closest player to the ball then he should keep
//chasing it
if (player.isClosestTeamMemberToBall()) {
player.Steering().SetTarget(player.Ball().Pos());
return;
}
//if the player is not closest to the ball anymore, he should return back
//to his home region and wait for another opportunity
player.GetFSM().ChangeState(ReturnToHomeRegion.Instance());
}
#Override
public void Exit(FieldPlayer player) {
player.Steering().SeekOff();
}
}
I was wondering if someone could explain what purpose the the return keywords in the first two if statements of the Execute() method serve?
Thanks
In this case it's mainly a formatting alternative to a series of else if clauses. It is logically equivalent to
if (<condition>) {
<code>
} else if (<condition>) {
<code>
} else {
<code>
}

Categories