Question

In: Computer Science

Please code the following, using the language java! Build a simple calculator that ignores order of...

Please code the following, using the language java!

Build a simple calculator that ignores order of operations. This “infix” calculator will read in a String from the user and calculate the results of that String from left to right. Consider the following left-to-right calculations:

"4 + 4 / 2"
"Answer is 4"   //not 6, since the addition occurs first when reading from left to right
“1 * -3 + 6 / 3”
“Answer is 1”   //and not -1Start by copying the driver code below.

Read this program and notice the comments before you proceed –your assignments in the lecture section will require you to comment accordingly, or they will drop a complete letter grade! Begin tracing the program in main, and your code will go in the calculate() function, so start writing code there. Hints:

  • Build the starter code using a snippet below.
  • Assume spaces between all numbers and operators.
  • If a number is negative (like -3), there will be no space between the sign and the number. Use Scanner and nextInt() to read each integer. Use Scanner and what operation to read a single character? (our operator?).
  • You can also use StringTokenizer to do these tasks as well.
  • Using the comments below, can you write the regular expression that would recognize this grammar?'
import ?; /*
 * InFixCalc, V0.0 (concept borrowed from Carol Zander's Infix Calculator)
 * Complete the calculate() function below to build a simple, infix
 * calculator that evaluates a compound expression from left to right,
 * regardless of operator precedence
 *
 * Example: " 1 * -3 + 6 / 3"
 * Execution: calculate 1 * -3 first, then -3 + 6 next, then 3 / 3
 * last to obtain the value 1
*
* Solution by 
*/
public class InFixCalc {
    //example pattern: "3 + 5"
    //general pattern: <lhs='3'> <operation='+'> <rhs='5'> //extended pattern:     ...  
    //special case: 
    //other special cases?

    public static void main(String[] args) { //String input = "4 + 4";
        //String input = "4 + 4 / 2";
        //String input ="1 * -3";
        String input ="1 * -3 + 6 / 3";
        //String input ="5";
        //String input ="-5";
        int answer = calculate(input);
        System.out.println("Answer is " + answer);
    }

//preconditions: all binary operations are separated via a space
//postconditions: returns the result of the processed string
    public static int calculate(String input) {
        int lhs,rhs; //short for left-hand & right-hand side
        char operation;
        /*todo: your name and code goes here*/
        /*You need a Scanner(or StringTokenizer) to get tokens
          *Then you need a loop, and switch inside that loop*/
        return lhs;
    }
}

Solutions

Expert Solution

If you have any doubts, please give me comment...

import java.util.*;

/*

* InFixCalc, V0.0 (concept borrowed from Carol Zander's Infix Calculator)

* Complete the calculate() function below to build a simple, infix

* calculator that evaluates a compound expression from left to right,

* regardless of operator precedence

*

* Example: " 1 * -3 + 6 / 3"

* Execution: calculate 1 * -3 first, then -3 + 6 next, then 3 / 3

* last to obtain the value 1

*

* Solution by

*/

public class InFixCalc {

    // example pattern: "3 + 5"

    // general pattern: <lhs='3'> <operation='+'> <rhs='5'> //extended pattern: ...

    // special case:

    // other special cases?

    public static void main(String[] args) { // String input = "4 + 4";

        // String input = "4 + 4 / 2";

        // String input ="1 * -3";

        String input = "1 * -3 + 6 / 3";

        // String input ="5";

        // String input ="-5";

        int answer = calculate(input);

        System.out.println("Answer is " + answer);

    }

    // preconditions: all binary operations are separated via a space

    // postconditions: returns the result of the processed string

    public static int calculate(String input) {

        int lhs, rhs; // short for left-hand & right-hand side

        char operation;

        /* todo: your name and code goes here */

        /*

         * You need a Scanner(or StringTokenizer) to get tokens Then you need a loop,

         * and switch inside that loop

         */

        Scanner scnr = new Scanner(input);

        lhs = scnr.nextInt();

        while(scnr.hasNext()){

            operation = scnr.next().charAt(0);

            rhs = scnr.nextInt();

            switch(operation){

                case '+':

                    lhs += rhs;

                    break;

                case '-':

                    lhs -= rhs;

                    break;

                case '*':

                    lhs *= rhs;

                    break;

                case '/':

                    lhs /= rhs;

                    break;

            }

        }

        return lhs;

    }

}


Related Solutions

Java Language Only Use Java FX In this project we will build a BMI calculator. BMI...
Java Language Only Use Java FX In this project we will build a BMI calculator. BMI is calculated using the following formulas: Measurement Units Formula and Calculation Kilograms and meters (or centimetres) Formula: weight (kg) / [height (m)]2 The formula for BMI is weight in kilograms divided by height in meters squared. If height has been measured in centimetres, divide by 100 to convert this to meters. Pounds and inches Formula: 703 x weight (lbs) / [height (in)]2 When using...
Using C# Windows App Form Create a simple calculator using +,-,*,/ Please show code GUI Code...
Using C# Windows App Form Create a simple calculator using +,-,*,/ Please show code GUI Code for calculator menus radio button input text boxes
Java For this project, we want to build a calculator program that can perform simple calculations...
Java For this project, we want to build a calculator program that can perform simple calculations and provide an output. If it encounters any errors, it should print a helpful error message giving the nature of the error. You may use any combination of If-Then statements and Try-Catch statements to detect and handle errors. Program Specification Input Our program should accept input in one of two ways: If a command-line argument is provided, it should read input from the file...
create scientific calculator using java language with OOP rule and interfaces.
create scientific calculator using java language with OOP rule and interfaces.
Write a simple Calculator program using Scheme programming language. It should be able to do following...
Write a simple Calculator program using Scheme programming language. It should be able to do following operations: "+", "-", " * *, "/". the format when using the calculator function should be (calculator(operand1 operation operand2)) -> (calculator(2 + 5)) should give the output of 7.
Using Java (Swing) language(please hard code)... Create a program that has a textfield for the user...
Using Java (Swing) language(please hard code)... Create a program that has a textfield for the user to type in a set of input. Below that textfield have the following controls to show string manipulations: (1) A button that will change the entire textfield’s current text to uppercase. (2) A button with its own textfield for a search value, that will tell the position the search value appears in the textfield above. (3) A button that reports the current number of...
TASK: Using stack functions, write a program in C++ language that acts as a simple calculator,...
TASK: Using stack functions, write a program in C++ language that acts as a simple calculator, reading an infix algebraic expression with numbers and simple operations: +, -, *, / , (, and ). The program converts an infix expression into an equivalent postfix expression, and then evaluates the postfix expression, and then prints the result if input expression is correct otherwise prints error messages. Your program must interact with the user until the user quits.    REQUIREMENTS: - Your...
Please use Java language in an easy way with comments! Thanks! Create a calculator that uses...
Please use Java language in an easy way with comments! Thanks! Create a calculator that uses an array of buttons for numbers from 0-9, the . for decimals, and for operators +, -, * ,/ and = as well as a JTextfield that displays the current value or the result. Use ActionListeners and LayoutManagers appropriately. The example below shows how to determine which button has been clicked. ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println(actionEvent.getActionCommand()); }...
C language only please and please make a simple code Write a function that will find...
C language only please and please make a simple code Write a function that will find whether there exist two integers that sum to the target integer. The function is to “return” three values.First, return “1” if the integers were found,return “-1” if your search was not successful.If you find two integers which add up to the target value, you should return their respective index position inside the array. Suggested prototype:int TwoSumFunction(int arr[], int size, int target, int*index1, int* index2);Inside...
Using python as the coding language please write the code for the following problem. Write a...
Using python as the coding language please write the code for the following problem. Write a function called provenance that takes two string arguments and returns another string depending on the values of the arguments according to the table below. This function is based on the geologic practice of determining the distance of a sedimentary rock from the source of its component grains by grain size and smoothness. First Argument Value Second Argument Value Return Value "coarse" "rounded" "intermediate" "coarse"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT