Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating commands for a terminal app in Java

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

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?

like image 424
h.demoff Avatar asked Aug 13 '15 15:08

h.demoff


1 Answers

You could 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 good practice to keep your variables lower cased.

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

like image 123
nLee Avatar answered Sep 21 '22 22:09

nLee