【问题标题】:How to add a search method as command input如何将搜索方法添加为命令输入
【发布时间】:2017-01-09 11:05:26
【问题描述】:

我正在做一个程序,添加参与者、参与者的结果和体育比赛的事件。我希望能够通过将事件名称写为命令来打印每个事件的所有结果。然后程序应该在我的arrayList 中搜索该事件并查看它是否存在,如果存在则打印出结果。 我有一种在arraylist 中搜索事件的方法,但是我无法将方法用作命令。我知道使用event result 之类的常用方法然后在其中添加方法会更容易,但要求您通过命令搜索列表中的事件。

boolean running = true;
while(running) {
    System.out.print("Command> ");
    String cmd = readString().toLowerCase();
    if (cmd.equals("message")) printMessage();
    else if (cmd.equals("add participant")) addParticipant(); 
    else if (cmd.equals("check participant")) listParticipant();
    else if (cmd.equals("remove participant")) removeParticipant(); 
    else if (cmd.equals("add result")) addResult();
    else if (cmd.equals("participant")) listParticipantResult();
    -> //else if (cmd.equals(findEvent()) listEvent();
    else if (cmd.equals("end")) {
        System.out.println("Exit!"); 
        running = false;
    } else System.out.println("Wrong command!");

}

【问题讨论】:

  • 您应该添加一个示例,说明您可以输入的命令和应该调用的方法(或如何使用您的搜索事件方法)。目前,我们只能假设一些模式。

标签: java input methods command


【解决方案1】:

假设您的命令将直接是事件名称。前任。体育竞技

    // Above all if else
    //assuming cmd will be directly your event name. search for event name in eventList if it exists then call findEvent method with eventName( here it will be cmd) as parameter.

    } else if (eventList.contains(cmd)) {
        findEvent(cmd);
    }

假设你的命令会找到

    //Above all if else
    //split the input as find saparate and other remaining string as eventName
    } else if (cmd.startsWith("find")) {
        String eventName = cmd.substring(4, cmd.length());
        findEvent(eventName);
    }

【讨论】:

    【解决方案2】:

    如您所说,如果您要搜索事件名称并且您希望命令看起来像这样:“find yourEventName”,那么您需要在最后一个else if 语句中检查该命令是否是“找到你的事件名称”,然后拆分该字符串,只得到“你的事件名称”。当你有了它时,只需调用你的方法findEvent(),并将事件名称作为参数,并在该方法中执行任何你想要的事件,如果你找到它。像这样:

    else if (cmd.equals("find yourEventName")) {
        String eventName = cmd.split(" ")[1];
        findEvent(eventName);
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-12-10
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2011-01-20
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多