The problem is trivial, but I am missing some very basic stuff here and unable to catch it. Please help. I am writing a simple calculator program to work with at command line. The source code is given below. The problem is when I use the calculator as
>java SwitchCalc 12 * 5
it throws a 'java.lang.NumberFormatException' for input string: "002.java" in the statement parsing 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);
}
}
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of String s.
*
is a wildcard that has a special meaning to the shell. It is expanded before it is even passed to the program.
In your case, the asterisk has been replaced by the names of all files in the directory, the first of which seems to be 002.java
. Trying to parse this string to an Integer results in the given exception.
By wrapping it in "*"
quotation marks, it is treated as a literal by the shell and simply passed to the program as is. Depending on the shell you are using, you should also be able to escape the asterisk with a \*
backslash.
See also the Wikipedia article about glob patterns.
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