I wrote a program in Java that accepts input via command line arguments.
I get an input of two numbers and an operator from the command line.
To multiply two numbers, I have to give input as e.g. 5 3 *
, but it's not working as written.
Why is it not accepting *
from the command line?
argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1] , and argv[argc] is always NULL.
Command line arguments are just values that are passed to an executable file when it is run. Also known as "command line switches" or "command line options," command line arguments are usually used to set program options, or to pass along the location of a file that the program should load.
A command-line argument is nothing but the information that we pass after typing the name of the Java program during the program execution. These arguments get stored as Strings in a String array that is passed to the main() function. We can use these command-line arguments as input in our Java program.
An argument, also called command line argument, can be defined as input given to a command line to process that input with the help of given command. Argument can be in the form of a file or directory. Arguments are entered in the terminal or console after entering command. They can be set as a path.
That's because *
is a shell wildcard: it has a special meaning to the shell, which expands it before passing it on to the command (in this case, java
).
Since you need a literal *
, you need to escape it from the shell. The exact way of escaping varies depending on your shell, but you can try:
java ProgramName 5 3 "*"
Or:
java ProgramName 5 3 \*
By the way, if you want to know what the shell does with the *
, try printing the content of String[] args
to your main
method. You'll find that it will contain names of the files in your directory.
This can be handy if you need to pass some filenames as command line arguments.
Wikipedia: glob
For example, if a directory contains two files,
a.log
andb.log
then the commandcat *.log
will be expanded by the shell tocat a.log b.log
Wikipedia: Escape character
In Bourne shell (
sh
), the asterisk (*
) and question mark (?
) characters are wildcard characters expanded via globbing. Without a preceding escape character, an*
will expand to the names of all files in the working directory that don't start with a period if and only if there are such files, otherwise*
remains unexpanded. So to refer to a file literally called"*"
, the shell must be told not to interpret it in this way, by preceding it with a backslash (\
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With