7

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?

1
  • That would be the short, "static", and poorly maintainable way to do it. To do it properly, so that commands can be "dynamic" (with possible flags and such, optional parameters) you gotta read on how to create a parser. Google it... Commented Aug 13, 2015 at 15:38

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

If it's just about reading the program parameters you can just add them behind the Java application call and access them through your args argument of your main method. And then you can loop through the array and search for the flags your program accepts.

2 Comments

No, I would have to be able to use them while the program is running, so I don't think that I could use arguments, could I?
No. So then the buffered reader is your choice. Unless you want to use an external parser library. (Depending on the size and professional maintainability of your software)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.