I am writing the most simple calculator in java that picks up command line arguments.Everything works fine, except the multiplication function. For some reason it picks up n
Enclose the entire calculation string in quotes, and split it yourself:
java Calculate "2 * 3"
That only uses a * for multiplication.
This has nothing to do with java, but with the command line, you need to use:
java Calculate 2 "*" 3
The reason is that *
is interpreted by the command line as a wildcard: it is replaced by all files in the folder, and luckily there is only one such. It is the default behavior of almost all (basic) shells. If you write it however between single ('*'
) or double ("*"
) quotes, the shell does not intepret it, but passes it as a character.
So what basically happens is that your call, is replaced by the cmd to:
java Calculate 2 <files in the directory> 3
In other words, java
doesn't even know you have ever used a wildcard, since it has been replaced before you called the program.
More info can be found here (although the website is designed for Linux shells, the ideas are generally applicable).
EDIT
As @PatriciaShanahan argues you can also place the entire expression in quotes, like:
java Calculate "2 * 3"
Note however that in that case, args[0]
will contain "2 * 3"
(and the length of args
will be 1
, thus you can't take benefit from the shell parsing your expression partly), so you will need to subdivide the string into parts yourself. And you don't drop the quotes completely.