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

theJ_SON
  • 3
  • 2
  • 6
    Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – OH GOD SPIDERS Oct 13 '17 at 11:49

2 Answers2

2

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

Use .equals() instead.

Neo
  • 3,534
  • 2
  • 20
  • 32
  • Downvotes are happily accepted **if followed by constructive comments**. – Neo Oct 13 '17 at 11:58
  • why did the if(args.length == 0) work then, if you don't mind me asking? – theJ_SON Oct 13 '17 at 11:59
  • 1
    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... – assembler Oct 13 '17 at 12:05
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.

dbencs
  • 64
  • 3