2017-10-13 83 views
0

我试图检测数组的位置0中的字符串的值,但尽管字面上复制粘贴值我检查对它未能检测到相似性。使用字符串数组选择(java)

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;} 

     } 

    } 

对于上下文,我使用的是Bukkit库。当onCommand方法被调用时,args []数组被传递给它。我已经从我的代码中复制粘贴了“破碎”和“放置”到将args []传递给此方法的输入,但它仍然返回false。

任何帮助,将不胜感激

+6

可能的重复[如何比较Java中的字符串?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) –

回答

2

字符串在Java中的对象,并将它们用比较==给地址比较,而不是你所期望的一个。

改为使用.equals()

+0

Downvotes愉快地接受**如果后面是建设性评论**。 – Neo

+0

为什么if(args.length == 0)工作呢,如果你不介意我问? –

+1

因为'args.length'返回一个原始的'int','0'也是一个原始的'int' ...如果你想比较字符串,你应该继续使用'equalsIgnoreCase' ... – assembler

0

==是“是给定的两个参数相同的参考”运算符,你要使用的是类String的.Equals()函数。 建议:为避免类似硬编码字符串的错误,请使用处理可能的字符串参数的类。