Creating commands for terminal applications in Java

I'm new to programming. I'm creating an application that runs only on the command line I found that I could read input from the command line using BufferedReader

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();

What I need to do now is find a way to create different "commands" and use them by typing them on the command line However, these commands may have to be used multiple times Do I have to use some kind of command design pattern and a huge switch statement (which seems wrong to me)? I want to avoid using additional libraries

Is there anyone with more experience who can help me?

Solution

You can try something like this:

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");
}

It is a good practice to keep the variables in a low range

I would say the same! Input. Equalsignorecase ("stop") is better than input Equalsignorecase ("stop") = = false is more readable, although the two are logically equivalent

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>