Using * at the command line in a Java program

The problem is trivial, but here I missed some very simple things and could not catch it. Please help. I am writing a simple calculator program to work on the command line. The source code is given below. The problem is that I use the calculator as

>java SwitchCalc 12 * 5 

it throws "java.lang.NumberFormatException" for the input line: "002.java" in the expression expressing the second int from args [2]:

 int value2 = Integer.parseInt(args[2]) 

Later I tried the following, it worked.

 >java SwitchCalc 12 "*" 5 12 * 5 = 60 

What am I missing?

 /* User will input the expression from command-line in the form: >java SwitchCalc value1 op value2 where, value1, and value2 are integer values op is an operator in +, -, *, /, % Program will evaluate the expression and will print the result. For eg. >java SwitchCalc 13 % 5 3 */ class SwitchCalc{ public static void main(String [] args){ int value1 = Integer.parseInt(args[0]), value2 = Integer.parseInt(args[2]), result = 0; switch(args[1]){ case "+": result = value1 + value2; break; case "-": result = value1 - value2; break; case "*": result = value1 * value2; break; case "/": result = value1 / value2; break; case "%": result = value1 % value2; break; default: System.out.printf("ERROR: Illegal operator %s.", args[1]); break; } System.out.printf("%d %s %d = %d", value1, args[1], value2, result); //System.out.println(value1 + " " + args[1] + " " + value2 + " = " + result); } } 
+6
source share
1 answer

* is a wildcard that is of particular importance to the shell. It expands before it is even transferred to the program.

In your case, the asterisk was replaced with the names of all the files in the directory, the first of which seems to be 002.java . Attempting to parse this string on Integer throws the specified exception.

Wrapping it in quotation marks "*" , it is processed by the shell as a literal and simply passed to the program as is. Depending on the shell you are using, you can also avoid the asterisk with a backslash \* .

See also the Wikipedia article on glob templates .

+6
source

All Articles