可能有一个类似的问题,但我不知道我正在寻找的确切内容。
我有一个名为Command
的类
package loopturn.loanbot.main;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Command extends ListenerAdapter implements CommandInterface {
private String command;
private CommandExecutor executor;
public Command(String command, CommandExecutor executor) {
this.command = command;
this.executor = executor;
}
public Boolean onCommand() {
return null;
}
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] messageSplitBySpace = event.getMessage().getContentRaw().split(" ");
if(messageSplitBySpace[0].startsWith("!")) {
if(messageSplitBySpace[0].equalsIgnoreCase("!" + command)) {
executor.onCall(event);
}
}
}
}
我为每个命令创建一个新命令。看起来很简单,对吧。那么,当命令运行但不存在时(命令通过发送以 '!'
开头的消息开始),我该如何做到这一点,它告诉他们它不存在。
我有一个想法,创建另一个类来接收命令,然后在聊天中说出命令时调用命令,但感觉这不是正确的解决方案。我想看看是否有人能想出更好的方法来做到这一点。
最佳答案
您可以拥有一个查找表,并在未找到命令时返回默认值。
execute( String command ) {
Command c = map.get(command)
if (c = null) {
c = new EmptyCommand()
}
c.run();
}
这样,如果找到命令,则执行它,如果没有找到,则执行一个不执行任何操作的 EmptyCommand
(或者在您的情况下,向用户显示“无效命令”消息)或类似的东西)。
关于java - 如果所有对象都返回 false,如何触发某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59795923/