Reputation: 41
I'm trying to create a basic calculator. Here is my code:
public class Calc2 {
public static void main(String[] args) {
String[] calcArray;
calcArray = new String[3];
calcArray[0] = args[0];
calcArray[1] = args[1];
calcArray[2] = args[2];
double result = 0;
if (args.length == 3) {
double firstNumber = Double.parseDouble(args[0]);
int operator = args[1].charAt(0);
double secondNumber = Double.parseDouble(args[2]);
System.out.print(args[0] + " " + args[1] + " " + args[2] + " = ");
switch (operator)
{
case ('+'):
result = firstNumber + secondNumber;
break;
case ('-'):
result = firstNumber - secondNumber;
break;
case ('*'):
result = firstNumber * secondNumber;
break;
case ('/'):
result = firstNumber / secondNumber;
break;
default:
System.out.println("Invalid Operator selected");
}
System.out.printf(" " + result);
}
else
{
System.out.println("Incorrect arguments quantity");
}
}
}
Seems that "-","+","/" operators works correctly, but when i try to execute multiplication in this code, for example:
java Calc2 4 * 3
Program displays following result:
Incorrect argument quantity
Please explain, why it happens and how to fix it. Thanks.
Upvotes: 3
Views: 691
Reputation: 18825
*
is expanded by the shell, therefore you'll get list of files as arguments. You need to escape:
java Calc2 4 "*" 3
Upvotes: 2
Reputation: 178263
The *
character typed on the command line is interpreted by the shell as a globbing character, meaning all files in the current directory. The command line being fed to Java is something like
3 Calc2.class Calc2.java 4
plus any other files that may be present.
Escape it in the shell (or single-quote it to avoid shell interpretation).
java Calc2 3\* 4
or
java Calc2 3 '*' 4
Upvotes: 7