Java Minecraft插件问题 - 没有响应if语句?

时间:2017-01-30 14:15:14

标签: java plugins minecraft

所以我正在为Minecraft服务器制作一个简单的代码兑换插件。有什么奇怪的是当我输入/兑换(有效代码)时,没有任何反应,尽管它应该......有效的代码是用户输入到插件配置中的代码。

这是我的代码......

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{   


    //Assigns the commands chosen in config to strings
    String commandChosen1 = this.getConfig().getString("Command for code 1");
    String commandChosen2 = this.getConfig().getString("Command for code 2");
    String commandChosen3 = this.getConfig().getString("Command for code 3");

    //Assigns the codes to strings
    String validCode1 = this.getConfig().getString("Valid Code 1");
    String validCode2 = this.getConfig().getString("Valid Code 2");
    String validCode3 = this.getConfig().getString("Valid Code 3");

    //If the redeem command is sent from a player
    if(cmd.getName().equalsIgnoreCase("redeem") && sender instanceof Player)
    {
        //Casts the sender to a new player.
        Player player = (Player) sender;

        //Creates object hasUSed to store whether or not the player has already redeemed a code
        Object hasUsed = this.getConfig().get(player.getName());


        //Gives an error message of the arguments don't equal 1.
        if(args.length != 1)
        {
            player.sendMessage(ChatColor.DARK_RED + "Please enter a valid promo code. Find them on our twitter!");
        }



        if(args.length == 1)
        {
            //If the player hasn't used the code yet and the arguments given are equal to a code then give them the reward...
            if(args[0] == validCode1 && hasUsed == null)
            {
                this.getConfig().set(player.getName(), 1);
                player.sendMessage(ChatColor.GREEN + "Promo code successfully entered!");
                if(commandChosen1 == "xp")
                {
                Bukkit.dispatchCommand(player, commandChosen1 + getConfig().getString("XP Given") + "L" + " " + player.getName());
                }
            }

        }

        return true;

    }
    return false;
}

问题出现在“if(args [0] == validCode1&& hasUsed == null)”上。如果这些事情都检查出来,应该发生的代码不会发生,我也不知道为什么。

1 个答案:

答案 0 :(得分:1)

确保在比较字符串时使用equals()。使用commandChosen1 == "xp"比较字符串引用而不是值;使用commandChosen1.equals("xp")或者您更喜欢"xp".equals(commandChosen1)

此外,

虽然可以使用包含空格的键值的this.getConfig().getString(),但它可能会使配置文件难以阅读和混乱。每当我设计插件时,我都会设计我的config.yml

VoteGUI:
  message: 'hello'

然后运行this.getConfig().getString("VoteGUI.message");

对于你,我建议这样的事情

Promo-Codes:
    validCode1: 'insert code here'
    validCode2: 'insert code here'
    validCode3: 'insert code here'

然后将其放入onCommand方法:

String validCode1 = this.getConfig().getString("Promo-Codes.validCode1");
    String validCode2 = this.getConfig().getString("Promo-Codes.validCode2");
    String validCode3 = this.getConfig().getString("Promo-Codes.validCode3");

如果这不能解决问题,请复制并粘贴从控制台抛出的异常,我可能会提供进一步的帮助