Question

In: Computer Science

Create a program named CmdLineCalc.java that works like a simple calculator. You'll run this program from...

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.

Solutions

Expert Solution

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);
   }

}


Related Solutions

Create a program using python that provides a simple calculator: Requires a login with a prompt...
Create a program using python that provides a simple calculator: Requires a login with a prompt for a username and a password prior to using the calculator If username and password are incorrect, the program should re-prompt to re-enter correct username and password Once logged in, the user should have access to the calculator and should have the ability for the following mathematical operators: Addition Subtraction Multiplication Division Square Root PI Exponents
In this program, you'll create a program that utilizes an enumerated data type to manipulate the...
In this program, you'll create a program that utilizes an enumerated data type to manipulate the array.   Here are the requirements: Write a program that contains an enumerated data type named Letters.    In the declaration, include the following three enumerators: ALPHA, BETA, DELTA. Then, create an array of integers three elements long. The array should be initialized to 0 using a 1-element initialization list. Instead of using integers as subscripts, use the enumerators from your enumerated data type to assign...
11.1 Simple Arithmetic Program Using the instructions from Week 1 Lab, create a new folder named...
11.1 Simple Arithmetic Program Using the instructions from Week 1 Lab, create a new folder named Project01. In this folder create a new class named Project01. This class must be in the default package. Make sure that in the comments at the top of the Java program you put your name and today's date using the format for Java comments given in the Week 1 Lab. For this lab, you will write a Java program to prompt the user to...
Process: In this lab, you will be implementing a simple “Bop-it!”-like game. Your program will run...
Process: In this lab, you will be implementing a simple “Bop-it!”-like game. Your program will run for a single game. Start with implementing a “start menu”, output a line asking the user to push a keyboard key to start and wait for the user to push a key. The game will involve printing a line telling the user which key to press (chosen randomly by the program) and will wait a certain time for a response. After each successful action...
Create an ASP.Net Website using Visual Studio with C#: Create a simple calculator that has 3...
Create an ASP.Net Website using Visual Studio with C#: Create a simple calculator that has 3 text boxes: 2 of them to enter numbers, the 3rd one displays the results Create 4 buttons to add, subtract, multiply, and divide Prevent the user from entering text in the number fields Display a message indicating “cannot divide by” when the user click “/” and there is a zero the in the second box Create two additional buttons: - One to store data...
Java program Create a public method named saveData for a class named Signal that will hold...
Java program Create a public method named saveData for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp...
Write a program named FinalExamProgram2 that reads numbers from a file (which you will create using...
Write a program named FinalExamProgram2 that reads numbers from a file (which you will create using Notepad) into a one-dimensional array and then analyzes the numbers as described below. Your program must use loops to read the numbers into the array and to analyze the contents of the array. The program’s main function should do the following:  Read eight floating-point numbers from the file named numbers.txt into a onedimensional array, displaying each number on the screen.  Pass the...
An exception with finally block lab. Create a new class named ReadArray Create simple array and...
An exception with finally block lab. Create a new class named ReadArray Create simple array and read an element using a try block Catch any exception Add a finally block and print a message that the operation if complete
1. Specification Write a C program to implement a simple calculator that accepts input in the...
1. Specification Write a C program to implement a simple calculator that accepts input in the following format and displays the result of the computation: calc [operand_1] [operator] [operand_2] The operands operand_1 and operand_2 are non-negative integers. The operator is one of the following: addition (+), subtraction (-), multiplication (x), division (/) and modulo (%). Note: For the multiplication operator, use letter ‘x’. If you use the asterisk ‘*’, your program will not work properly 2. Implementation • The program...
Change Calculator Task: Create a program that will input a price and a money amount. The...
Change Calculator Task: Create a program that will input a price and a money amount. The program will then decide if there is any change due and calculate how much change and which coins to hand out. Coins will be preferred in the least number of coins (starting with quarters and working your way down to pennies). Input: total_price, amount_tender allow the user to input 'q' for either value if they want to quit the program Validate: total_price cannot be...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT