user6069863
user6069863

Reputation:

calculator Java adding numbers

So, my question is, how do I turn this make my calculator app be able to take input like this, 100 * 2 / 2 + 5 and make it return the sum of it? or maybe even somehow make it use ( ) brackets..?

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter number: ");
        String input = scanner.nextLine();

        System.out.println("Enter number 2: ");
        String input2 = scanner.nextLine();

        System.out.println("Enter operator ");
        String op = scanner.nextLine();

        int intEnter1 = Integer.parseInt(input.toString());
        int intEnter2 = Integer.parseInt(input2.toString());

        if (op.contains("+")) {
            System.out.println(intEnter1 + intEnter2);
        }

        if (op.contains("-")) {
            System.out.println(intEnter1 - intEnter2);
        }

        if (op.contains("*")) {
            System.out.println(intEnter1 * intEnter2);
        }

        if (op.contains("/")) {
            double intEnter1Double = (double) intEnter1;
            double intEnter2Double = (double) intEnter2;
            System.out.println(intEnter1Double / intEnter2Double);
        }
    }
}

Upvotes: 2

Views: 757

Answers (3)

Milan
Milan

Reputation: 1900

There is also a very good library for evaluating math expressions called exp4j.

You can do something like this:

Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
    .variables("x", "y")
    .build()
    .setVariable("x", 2.3)
    .setVariable("y", 3.14);
double result = e.evaluate();

Upvotes: 3

Aliaxander
Aliaxander

Reputation: 2617

You have to convert your expression to Reverse Polish notation. The idea is to transform complex expression to such form that it will be possible to calculate the result using the following algorithm:

  1. expression is parsed from left to right
  2. numbers are pushed to stack
  3. if an operator occured, the correspondent amount of numbers a popped from stack (1 for unary operator, 2 for binary) and the operation is performed on them

For example, given the input:

5 + ((1 + 2) × 4) − 3

the notation will as following:

5 1 2 + 4 × + 3 −

Upvotes: 1

cralfaro
cralfaro

Reputation: 5948

I found a library that makes that evaluate expressions. You can try this.

http://javaluator.sourceforge.net/en/home/

Double value = new DoubleEvaluator().evaluate(expression);

But this library make all work for you and maybe you want to do by yourself the algorithm no?

Upvotes: 1

Related Questions