In: Computer Science
Create a program named CmdLineCalc.java that works like a simple calculator. You'll run this program from the command line:
$ java CmdLineCalc 1 + 2 3.0 $ java CmdLineCalc 1 - 2.5 -1.5 $ java CmdLineCalc 3 + 4 - 5 2.0 $ java CmdLineCalc 6.5 - 7 + 8 7.5
To keep it simple, your program only needs to support addition (+) and subtraction (-). You may assume that, starting with the first argument, every other argument will be a number. The arguments at odd indexes in the array will be operators. There is no limit to the number of arguments, that is, until the computer runs out of memory. The program should display the answer rounded to one decimal place.
There are three types of errors you need to handle: 1) the user might forget to give you command-line arguments, 2) the expression itself might be incomplete, and 3) the user might use operators you don't support. Here is what you should output in those cases:
$ java CmdLineCalc Missing expression $ java CmdLineCalc 1 + Invalid expression $ java CmdLineCalc 2 % 3 Invalid operator: %
When an error occurs, display the appropriate message and call System.exit() to terminate the program. Use a status of 1 to indicate that an error occurred. (By default, programs exit with a status of 0, meaning success.)
Any answers will receive a like.
public class CmdLineCalc {
public static void main(String[] args) {
if(args.length==0) {
System.out.println("Missing expression");
System.exit(1);
}
double result = 0.0;
try {
result =
Double.parseDouble(args[0]);
for(int i=1;i<args.length;)
{
if(args[i].equals("+")) {
result += Double.parseDouble(args[i+1]);
i=i+2; //used + and next number also
}
else
if(args[i].equals("-")) {
result -= Double.parseDouble(args[i+1]);
i=i+2; //used - and next number also
}
else {
System.out.println("Invalid operator:
"+args[i]);
System.exit(1);
}
}
}catch(Exception e) {
System.out.println("Invalid expression");
System.exit(1);
}
System.out.printf("%.1f",
result);
}
}