How can I execute actions of a program by putting a '-' [closed]

1

I was wondering how the compilers like GCC or Java could execute different actions just by putting a '-' .

e.g:

or also

in gcc is the same

EDIT: I quote the example of gcc, not because I want to implement it in a C ++ program, but to put it as a simple example (forgive the redundancy). Basically I just want to know how to add it to a Java program.

    
asked by Álvaro Rodrigo 18.12.2018 в 21:56
source

1 answer

6

To achieve what you want, you must evaluate the parameters that your program has received when invoked from the command line.

In java, for example, these parameters arrive as arguments of the main() method, as an array of character strings, which is traditionally called args (of arguments).

Basically, then, you evaluate what comes in each element of that arrangement. Look at this simple example where it is for the arguments. If I have not received any valid arguments, I print the help of the program:

    public static void main (String args[]) {
        boolean correcto = false;
        int result = 0;
        for (String arg : args) {
          switch (arg) {
            case "-opcion1":
              System.out.println("Felicitaciones, ha utilizado la opcion1");
              correcto = true;
              break;
            case "-opcion2":
              System.out.println("Felicitaciones, ha utilizado la opcion2");
              correcto = true;
              break;
          }
        }
        if (!correcto) {
            System.out.println("Uso: programa [-opcion1] [-opcion2]");
            result = 1;
        }
    }

When I invoke it, I get these answers:

> java MiClase

Uso: programa [-opcion1] [-opcion2]

> java MiClase -opcion1
Felicitaciones, ha utilizado la opcion1

> java MiClase -opcion2 -opcion1
Felicitaciones, ha utilizado la opcion2
Felicitaciones, ha utilizado la opcion1

On this base idea, there are libraries that are of great help to make robust software in this area making a relatively simple programming. For example, Apache Commons CLI or picocli .

    
answered by 18.12.2018 / 22:48
source