简体   繁体   中英

How to evaluate the mathematical expression in Java?

I need to write a Java program to solve similar mathematical expressions like below. I am using ScriptEngineManager, but ScriptEngineManager is not a requirement; it could be any anything to solve my problem.

Let's take an example: exp = 100*(2**4) so answer should be 1600 but I am getting 204.

Consider ** as the power operator for example: (2**4 =>Math.pow(2,4));

Replacing ** with ^ is simply not working (getting wrong answer as shown above), without power operator ( ** ) everything is working fine, consider this example: (6*(4/2)+3*1) = answer 15 as expected. so I just need to handle ** .

Flow of Program:

  1. User take an input using input scanner.
  2. Get calculated value from input expression.

To evaluate power in java, please use Math.pow method:

var exp = 100 * Math.pow(2, 4);

There is no ** operator in java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM