Войти или зарегистрироваться

Помогите Убрать ошибку при отсутствии строки в конфиге

  • Автор темы Автор темы Sitafe
  • Дата начала Дата начала
Статус
Закрыто для дальнейших ответов.

Sitafe

Активный участник
Пользователь
Баллы
66
Ребят, привет. Помогите, люди добрые .
Ситуация такая:
Плагин берёт из конфига строку command и message и выполняет их, если они есть там.

При таком конфиге и коде всё работает как надо:
config.yml:
Код:
mobs:
  CHICKEN:
    message: 'Вы убили курицу, %player.'
    command: 'say %player убил курицу!'
Код:
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null)
            return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;
        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        String command = section.getString("command").replace("%player", killer.getName());
        String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        killer.sendMessage(message);
    }

Но, если из конфига я уберу либо command, либо message, то получается ошибка.
А если оставить command: "" - то в консоли пишется, что такая команда неизвестна, а
message: "" - отправляет пустое сообщение в чат, будто там что-то всё же есть.

Как сделать так, чтобы либо я мог безопасно просто убрать полную строку command или message, чтобы ничего не происходило (либо что-то одно из этого), либо оставить в кавычках пустые значения, для отключения данной функции?
 
Попробуй использовать конструкцию try catch
 
if (command! = null & & message! = null) {
//тут код
}
 
if (command! = null & & message! = null) {
//тут код
}
Только чтобы это работало, замену в строке
Код:
.replace("%player", killer.getName());
нужно делать внутри этого if. Ибо будет ошибка NullPointerException при попытке сделать replace.
 
У ConfigurationSection есть метод isSet, который вернёт тебе true если указано значение по пути. Если юзер уберет из конфига одну из строк, по идее, isSet вернет false.

Пользуясь этим методом, ты можешь проверить есть ли в конфиге нужная тебе строка и если она есть, выполнять какое-то действие
 
if (command! = null & & message! = null) {
//тут код
}
Код:
        if (command != null && message != null) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
            killer.sendMessage(message);
        }
При таком условии, убирается ошибка, но если что-то из одного отсутствует, то не выполняется ничего.

Я попробовал по отдельности, убрав это:
Код:
.replace("%player", killer.getName());

Финал вот:
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        String command = section.getString("command");
        String message = section.getString("message");

        if (command != null) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (message != null) {
            killer.sendMessage(message);
        }

    }

Решилось только то, что из конфига безопасно могу убрать command или message, но их нужно полностью стереть, интересно как отключить их, если вы кавычках ничего не будет.

И куда теперь приписать это:
.replace("%player", killer.getName());
.replace("&", "§");
 
У ConfigurationSection есть метод isSet, который вернёт тебе true если указано значение по пути. Если юзер уберет из конфига одну из строк, по идее, isSet вернет false.

Пользуясь этим методом, ты можешь проверить есть ли в конфиге нужная тебе строка и если она есть, выполнять какое-то действие
Не смог разобраться как это использовать :ninja:
 
Код:
        if (command != null && message != null) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
            killer.sendMessage(message);
        }
При таком условии, убирается ошибка, но если что-то из одного отсутствует, то не выполняется ничего.

Я попробовал по отдельности, убрав это:
Код:
.replace("%player", killer.getName());

Финал вот:
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        String command = section.getString("command");
        String message = section.getString("message");

        if (command != null) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (message != null) {
            killer.sendMessage(message);
        }

    }

Решилось только то, что из конфига безопасно могу убрать command или message, но их нужно полностью стереть, интересно как отключить их, если вы кавычках ничего не будет.

И куда теперь приписать это:
.replace("%player", killer.getName());
.replace("&", "§");
Попробуй вот так.
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null)
            return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;
        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        try {
            String command = section.getString("command").replace("%player", killer.getName());
            String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
            killer.sendMessage(message);
        } catch (Exception e) {
            
        }
    }
 
Попробуй вот так.
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null)
            return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;
        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        try {
            String command = section.getString("command").replace("%player", killer.getName());
            String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
            killer.sendMessage(message);
        } catch (Exception e) {
           
        }
    }
Не работает, пишет ошибку в catch (Exception e), где e - уже используется.
 
Примерно так. Писал с телефона
HTML:
if (section.isSet("твоя.секция.command") {
//достаешь значение command и делаешь что нужно
}
Как-то так?
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        String command = section.getString("command").replace("%player", killer.getName());
        String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
        if (section.isSet("command")) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (section.isSet("message")) {
            killer.sendMessage(message);
        }
Не работает :cry:
 
Не работает, пишет ошибку в catch (Exception e), где e - уже используется.
Логично, что надо поменять имя этой переменной, ибо уже такое отвечает за ивент. И это костыль. Прислушайся к ответу выше
 
Как-то так?
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        String command = section.getString("command").replace("%player", killer.getName());
        String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
        if (section.isSet("command")) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (section.isSet("message")) {
            killer.sendMessage(message);
        }
Не работает :cry:
потому что ты реплейс делаешь быстрее, чем проверяешь есть ли такое в конфиге
 
Логично, что надо поменять имя этой переменной, ибо уже такое отвечает за ивент. И это костыль. Прислушайся к ответу выше
Да, переменную там пытался поменять, ошибка её пропала, но ситуация не решилась.
 
Как-то так?
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        String command = section.getString("command").replace("%player", killer.getName());
        String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
        if (section.isSet("command")) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (section.isSet("message")) {
            killer.sendMessage(message);
        }
Не работает :cry:
HTML:
[CODE]    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        if (section.isSet("command")) {
               String command = section.getString("command").replace("%player", killer.getName());
               Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (section.isSet("message")) {
               String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
               killer.sendMessage(message);
        }[/CODE]
как-то так
 
потому что ты реплейс делаешь быстрее, чем проверяешь есть ли такое в конфиге
Вот код, всё работает, спокойно могу убрать command и message или даже обе, но это всё без repalce.
Код:
    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        String command = section.getString("command");
        String message = section.getString("message");
        if (section.isSet("command")) {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (section.isSet("message")) {
            killer.sendMessage(message);
        }
Подскажите код для replace.
 
HTML:
[CODE]    @EventHandler
    public void onEntityDeath (EntityDeathEvent e) {
        FileConfiguration config = this.plugin.getConfig();
        Player killer = e.getEntity().getKiller();
        if (killer == null) return;
        EntityType type = e.getEntity().getType();
        if (!config.getConfigurationSection("mobs").getKeys(false).contains(type.toString()))
            return;

        ConfigurationSection section = config.getConfigurationSection("mobs." + type);
        if (section.isSet("command")) {
               String command = section.getString("command").replace("%player", killer.getName());
               Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
        }
        if (section.isSet("message")) {
               String message = section.getString("message").replace("&", "§").replace("%player", killer.getName());
               killer.sendMessage(message);
        }[/CODE]
как-то так
блин, эти строки вписывал, но не убирал верхние, я был так близко :mad:
Огромное спасибо, работает!
 
Статус
Закрыто для дальнейших ответов.
Назад
Верх