2012-12-22 81 views
0

好吧我建立這個電子表格應用程序,我通過命令行界面實現,我有某些命令,例如退出,終止程序。需要幫助建立一個命令行接口的命令類在java

所以我有這樣的應用程序類,在那裏我有這些字段:

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時,應該創建一個新的電子表格。但是當我這樣做的時候,沒有什麼事情真的發生,所以你可以告訴我爲什麼?

+0

您的問題描述可能過於含糊,任何人真正知道什麼是錯的。 [SSCCE](http://sscce.org/)將爲您提供簡明扼要的答案。 –

+0

您是否保存電子表格? – tcb

回答

0

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

在此之前,我相信你正試圖在這個應用程序中使用命令模式。我建議你創建一個名爲'Command'的接口和一個'execute()'方法,然後在你所有的類中實現Command接口。如果您發現「NS」作爲命令行輸入只是新的命令創建實例爲

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

我可以請你給我一個如何做的例子嗎? :) –

+0

編輯我的答案 – Surez