Question

I currently have two classes Main and Command. They are both inside of the package emerica.simple So the classpath is emerica.simple.Main and emerica.simple.Command

In main I define a Boolean called spyblock

public class Main extends JavaPlugin{ public static boolean spyblock = true;

In command I am trying to access it and change it

public class Command implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (cmd.getName().equalsIgnoreCase("spyblocks")) {
        return true;
        if (Main.spyblock == true) {

            Main.spyblock = false;
        }
        else {
            Main.spyblock = true;
        }
    } 
    else 
    {
        return false;
    }
}

Hoe can I change this code so it works? I am trying to toggle main.spyblock this the command "Spyblocks"

Was it helpful?

Solution

Your code for altering spyblock is not reachable because of

if (cmd.getName().equalsIgnoreCase("spyblocks")) {
        **return true;**
        if (Main.spyblock == true) {

            Main.spyblock = false;
        }
        else {
            Main.spyblock = true;
        }
    } 

highlighted line. just move this like

if (cmd.getName().equalsIgnoreCase("spyblocks")) {

        if (Main.spyblock == true) {

            Main.spyblock = false;
        }
        else {
            Main.spyblock = true;
        }
        **return true;**
    } 

Hope this helps

OTHER TIPS

You have unreachable code :

if (cmd.getName().equalsIgnoreCase("spyblocks")) {
    return true;
     //unreachable code
    if (Main.spyblock == true) {

        Main.spyblock = false;
    }
    else {
        Main.spyblock = true;
    }
} 

That's why value of Main.spyblock doesn't change.

You returned your method just above your 2nd if i.e. return true;, that's why your if is not executing, you have to put return true; after your 2nd if-else condition.

If you just want to toggle it do it like this:

if (cmd.getName().equalsIgnoreCase("spyblocks")) {
   Main.spyblock = !Main.spyblock;
} 

I don't fully understsand what you are trying to do, but currently your code won't compile properly.

Try changing it to the following

public class Command implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (cmd.getName().equalsIgnoreCase("spyblocks")) {
        if (Main.spyblock == true) {
            Main.spyblock = false;
        }
        else {
            Main.spyblock = true;
        } 
        return true;
    }
    return false;
}

You can also change your logic, making it a bit simpler, since you do not have to check for both conditions, since you are always toggling it. Therefore just always set it to the opposite of what it currently is.

    Main.spyblock = !Main.spyblock;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top