Code:
public class Args {
public static void main(String[] args) {
if(args.length != 3) {
System.out.println("Wrong number of arguments");
return;
}
int num1 = Integer.parseInt(args[0]); // 1st argument from args
int num2 = Integer.parseInt(args[2]); // 3rd argument from args
String msg = args[0] + args[1] + args[2] + "=";
if(args[1].equals("+"))
msg += (num1 + num2);
else if(args[1].equals("-"))
msg += (num1 - num2);
else if(args[1].equals("x"))
msg += (num1 * num2);
else if(args[1].equals("/"))
msg += (num1 / num2);
else
msg = "Incorrect operator";
System.out.println(msg);
}
}
Output on command line:
C:\Desktop>java Args
Wrong number of arguments
C:\Desktop>java Args 16 + 4
16+4=20
C:\Desktop>java Args 16 - 4
16-4=12
C:\Desktop>java Args 16 x 4
16x4=64
C:\Desktop>java Args 16 / 4
16/4=4
C:\Desktop>java Args 16 # 4
Incorrect operator
So far everything was working fine. However, when I passed the below argument, I assumed that according to my code the output should have been Incorrect operator
, instead it returned Wrong number of arguments
. Everything after the ^
character is getting ignored. Why is this happening? I know ^
is used for exponents, apart from this does it have a special meaning in Java which causes the below ignoring behavior?
C:\Desktop>java Args 16 ^ 4
Wrong number of arguments