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...
Introduction to Java Programing Using Loop Create a simple calculator program using loop Ask user to...
Introduction to Java Programing Using Loop Create a simple calculator program using loop Ask user to input two numbers using scanner class Print the instruction of the menu for the calculator program Ask user to press 0 to Quit Ask user to press 1 to Add Ask user to press 2 to Substract Ask user to press 3 to Multiply Ask user to press 4 to Divide Perform correct calcuation based on user inputs and print the result Print error...
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...
For this assignment you will develop pseudocode and write a C++ program for a simple calculator....
For this assignment you will develop pseudocode and write a C++ program for a simple calculator. You will create both files in Codio. Put your pseudocode and C++ code in the files below. PSEUDOCODE FILE NAME: Calculator.txt C++ SOURCE CODE FILE NAME : Calculator.cpp DESCRIPTION: Write a menu-driven program to perform arithmetic operations and computations on a list of integer input values. Present the user with the following menu. The user will choose a menu option. The program will prompt...
use a financial calculator or a program such as Excel to answer the questions run your...
use a financial calculator or a program such as Excel to answer the questions run your answers to the nearest whole number. A. you purchase a stock for $9,500 and collect $350 at the end of each year in dividends. you sell the stock for $11,000 after 6 years what was the annual return on your $9, 500 investment? B. You purchased a building for a $750,000 collect annual rent (after expenses) of $110,000 and sell the building for $800,000...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT