0

I'm trying to detect the value of a string in position 0 of an array, but despite literally copy pasting the value I'm checking against it fails to detect the similarity.

    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    // boolean method must return true or false
    Player player = (Player) sender;        // casts the sender, from CommandSender, to class Player
    String ref = sender.getName();          // string 'ref' refer's to the sender's name
    boolean success = f;                    // Stores if code is executed correctly

    if(label.equalsIgnoreCase("blocks")) {  // if command sent is '/blocks'
        success = t;     // This code will work fine if args has no values
        if (args.length == 0) {

            some_code()

        }else{
            getLogger().info(args[0].toString());       // for debugging / prints out the 
            String arg0 = args[0].toString();
            if(arg0 == "broken") { // This is the bit that wont work. when args[0] is 'broken' the if statement passes to the else claus

                                  some_more_code()

            }else if(arg0 == "placed") {

                even_more_code()    
        }else {
                getLogger().info("I failed to run");    // for debugging     /     it constantly prints this error message
                success = f;}

        }

    }

For context I am using the Bukkit libraries. When the onCommand method is called, the args[] array is passed to it. I have literally copy-pasted the "broken" and "placed" from my code into the input that passes the args[] to this method, but it still returns false.

Any help would be much appreciated

1

2 Answers 2

3

Strings in Java are objects, and comparing them using == gives address comparison, not the one you'd expect.

Use .equals() instead.

Sign up to request clarification or add additional context in comments.

3 Comments

Downvotes are happily accepted if followed by constructive comments.
why did the if(args.length == 0) work then, if you don't mind me asking?
because of args.length returns a primitive int and 0 is also a primitive int... you should keep using equalsIgnoreCase if you wish to compare strings...
0

== is the "is the given two parameter the same reference" operator, what you want to use is the .Equals() function of the class String. Suggestion: to avoid anything like mismatching your hardcoded strings use a class which handles the possible string arguments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.