【问题标题】:Need help building command classes for a command line interface in java需要帮助为 java 中的命令行界面构建命令类
【发布时间】:2012-12-09 22:26:59
【问题描述】:

好的,我正在构建这个电子表格应用程序,我正在通过命令行界面实现它,其中我有某些命令,例如 exit,它会终止程序。

所以我有这个应用程序类,其中有这些字段:

private ArrayList<Spreadsheet> spreadsheets;
private Spreadsheet worksheet;

还有这个方法:

public void newSpreadsheet() {
  worksheet = new Spreadsheet();
  spreadsheets.add(worksheet);
}

然后我有一个如下所示的 CommandIntepreter 类:

package ui;

import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;

import ui.command.Command;
import ui.command.ExitCommand;
import ui.command.FailedCommand;
import ui.command.PrintCommand;
import ui.command.NewCommand;
import ui.command.ListCommand;
import ui.command.ChangeCommand;
import ui.command.SetCommand;
import ui.command.GetCommand;



import spreadsheet.*;
import spreadsheet.arithmetic.*;

public final class CommandInterpreter {

private CommandInterpreter() {
// The class should not be instanciated.
}

public static Command interpret(final Scanner scanner) {
final String keyword = scanner.next();
switch(keyword) {
  case "exit":
    return new ExitCommand();
  case "pws":
    return new PrintCommand();
  case "ns":
    return new NewCommand();
  case "ls":
    return new ListCommand();
  case "cws":
    return new ChangeCommand();
  case "set":
    return new SetCommand();
  case "get":
    return new GetCommand();

}
return new FailedCommand(
  String.format("Illegal start of command, \"%s\".", keyword));
}

}

然后我创建了如下所示的 NewCommand 类:

package ui.command;

import spreadsheet.Application;
import spreadsheet.Spreadsheet;

public final class NewCommand
 extends Command {

public void execute() {
 Application.instance.newSpreadsheet();
}
}

当我写 ns 时应该制作一个新的电子表格。但是当我这样做时,什么都没有发生,所以你能告诉我为什么会这样吗?

【问题讨论】:

  • 您的问题描述可能过于模糊,以至于任何人都无法真正说出问题所在。 SSCCE 将为您提供简明的答案。
  • 您保存电子表格吗?

标签: java command command-line-interface


【解决方案1】:

您必须调用 NewCommand 类的执行方法才能创建新的电子表格。我在您的代码中没有看到您这样做的任何地方。

在此之前,我相信您正在尝试在此应用程序中使用命令模式。我建议您创建一个名为“Command”的接口并使用方法“execute()”,然后在所有类中实现 Command 接口。如果您发现 'ns' 作为命令行输入,只需为 New Command 创建实例

case "ns":
Command nsCommand = new NewCommand();
nsCOmmand.execute();
return "SOME_MESSAGE"

【讨论】:

  • 我可以请你给我一个如何做到这一点的例子吗? :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 2018-02-06
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
相关资源
最近更新 更多