在Java中为终端应用程序创建命令 [英] Creating commands for a terminal app in Java

查看:126
本文介绍了在Java中为终端应用程序创建命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接触编程,我正在制作一个只在命令行中运行的应用程序。我发现我可以使用BufferedReader从命令行读取输入。

I'm new to programming, and I'm making an app that only runs in the command-line. I found that I could use a BufferedReader to read the inputs from the command-line.

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String Input = "";

while (Input.equalsIgnoreCase("Stop") == false) {
        Input = in.readLine();  
        //Here comes the tricky part
    }

    in.close();

我现在想做的是找到一种方法来创建不同的命令可以只使用在命令行中键入它们。但是这些命令可能需要多次使用。我必须使用某种命令设计模式与一个巨大的switch语句(这似乎不对我)?我想避免使用额外的图书馆

What I'm trying to do now is to find a way to create different "commands" that you could use just by typing them in the command-line. But these commands might have to be used multiple times. Do I have to use some kind of Command design pattern with a huge switch statement (that doesn't seem right to me)? I'd like to avoid using an extra library.

有更多经验的人,我可以帮助我吗?

Can someone with a bit more experience that me try to help me?

推荐答案

您可以尝试这样:

public static void main(String[] args) {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String input = "";
    try {
        while (!input.equalsIgnoreCase("stop")) {
            showMenu();
            input = in.readLine();
            if(input.equals("1")) {
                //do something
            }
            else if(input.equals("2")) {
                //do something else
            }
            else if(input.equals("3")) {
                // do something else
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void showMenu() {
    System.out.println("Enter 1, 2, 3, or \"stop\" to exit");
}

code>下壳。

我也会说!Input.equalsIgnoreCase(stop) Input.equalsIgnoreCase(stop)== false ,但两者在逻辑上是等价的。

I would also say that !Input.equalsIgnoreCase("stop") is much more readable than Input.equalsIgnoreCase("stop") == false although both are logically equivalent.

这篇关于在Java中为终端应用程序创建命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆