java - 带有非常量 case 的 switch 语句

标签 java command-line internationalization switch-statement

我正在完成这项作业,其中我使用命令行界面。我使用一个简单的 switch 语句来创建此命令行界面的控件,但是当我添加国际化支持作为我的作业的一部分时,由于需要保持常量,我的 switch 语句已损坏。我该如何解决这个问题?

public class Editor {

    private boolean running = true;

    public static ArrayList<String> command = new ArrayList<String>();

    Locale enLocale = new Locale("en", "GB");
    ResourceBundle messages = ResourceBundle.getBundle("BaseBundle", enLocale);
    String open = messages.getString("open");
    String saveas = messages.getString("saveas");
    String put = messages.getString("put");
    String rot90 = messages.getString("rot90");
    String mono = messages.getString("mono");
    String help = messages.getString("help");
    String quit = messages.getString("quit");
    String look = messages.getString("look");
    String undo = messages.getString("undo");
    private String get = messages.getString("get");

    Parser parser = new Parser();

    public Editor() {
    }

    public void run() {
        System.out.println("fotoshop");
        while (running) {
            command = parser.readInput();
            interpret(command);
        }
        System.out.println("fotoshop exiting");
    }

    public void interpret(ArrayList<String> command) {


        switch (command.get(0)) {
            case open: OpenCommand.execute();
            case saveas: SaveCommand.execute();
            case put: PutCommand.execute();
            case get: GetCommand.execute();
            case rot90: ApplyRot90.execute();
            case mono: ApplyMono.execute();
            case help: HelpCommand.execute();
            case quit: running = false;
            case look: LookCommand.execute();
            case undo;

        }
    }



}

最佳答案

我对 Java 中的国际化不太熟悉,但我认为您应该使用的一般模式是这样的:

Map<String, String> i18Map = new HashMap<>();
map.put("open", "open");    // English
map.put("abierto", "open"); // Spanish
map.put("ouvrir", "open");  // French
// other words/languages

换句话说,维护某种映射,可以将您想要支持的任何语言的命令映射到英语命令。然后,重构您的 switch 语句以打开这些英语语言常量而不是变量:

String input = parser.readInput();
String command = i18Map.get(input);

switch (command.get(0)) {
    case "open": OpenCommand.execute();
    case "saveas": SaveCommand.execute();
    case "put": PutCommand.execute();
    case "get": GetCommand.execute();
    // etc.
}

关于java - 带有非常量 case 的 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47129026/

相关文章:

Xcode 命令行工具 - 如何在终端中运行?

css - 哪些 UTF-8 语言可以在 HTML 中显示为 'safe' 而无需任何特定的表示调整?

internationalization - I18n 分段路由器 Phoenix

UTF-8编码问题(最后一个unicode字符是什么)

java - 如何使用数据对象而不是 String[][]

java - Hibernate ManyToOne 映射不在 PKey 上

java - tomcat8内存泄漏

Java 包与文件夹结构?有什么区别

shell - 如何定期保存程序输出的最后一行?

linux - Basename 带空格的文件名,并在命令 1 中使用带空格的文件名