Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

command line arguments java * is being overloaded to pick up filenames

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 names of the files from the current location. I have absolutely no idea why this happening, and how to turn it off...google was no help.

public class Calculate {

    public static void main(String[] args) {

        System.out.println(args[0] + " " + args[1] + " " + args[2]);

        if (args.length != 3) {
            System.out.println("<number1> <operator> <number2>");
        } else {

            final int num1 = Integer.parseInt(args[0]);
            final int num2 = Integer.parseInt(args[2]);
            switch (args[1]) {
            case "+":
                System.out.println(num1 + num2);
                break;
            case "-":
                System.out.println(num1 - num2);
                break;
            case "*":
                System.out.println(num1 * num2);
                break;
            case "/":
                System.out.println(num1 / num2);
                break;
            }
            System.out.println("\n");
        }
    }
}

enter image description here

like image 849
Jenny Avatar asked Feb 12 '23 05:02

Jenny


2 Answers

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.

like image 85
Willem Van Onsem Avatar answered Feb 13 '23 20:02

Willem Van Onsem


Enclose the entire calculation string in quotes, and split it yourself:

java Calculate "2 * 3"

That only uses a * for multiplication.

like image 42
Patricia Shanahan Avatar answered Feb 13 '23 20:02

Patricia Shanahan