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?
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.
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
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 (\
).