簡體   English   中英

需要幫助來為Java中的命令行界面構建命令類

[英]Need help building command classes for a command line interface in java

好的,我正在構建此電子表格應用程序,該應用程序是通過命令行界面實現的,在該界面中,我具有某些命令,例如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時應該制作一個新的電子表格。 但是當我這樣做時,什么也沒有發生,所以您能告訴我為什么嗎?

您必須調用NewCommand類execute方法才能創建新的電子表格。 我看不到您的代碼中的任何地方。

在此之前,我相信您正在嘗試在此應用程序中使用命令模式。 我建議您創建一個名為“ Command”的接口並使用一種方法“ execute()”,然后在所有類中實現Command接口。 如果您找到“ ns”作為命令行輸入,則只需為New Command創建實例即可

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM