Question:
Enter an expression with no parentheses. The number is smaller than 0-9, and the calculation result is output. All intermediate results are converted into an integer.
Example: input: 3 + 8x2/9-2
Output: 2
Function prototype
- Public int getMyRet (String str)
Analysis: This question is a little high-end. non-professional self-scholars like me have never studied compilation principles or other courses. It is very difficult to implement such a small compiler on their own, fortunately, this question is implemented in java, and I have seen such problems in java,
One way to solve this kind of problem is to implement the functions of the class compiler, which I cannot handle. However, there is also a cheap method in java, which is to add a brand new api after java 1.6, we can embed various scripting languages in java, so we can use the eval function in javascript very awkwardly.
Output The result directly! Let's take a look at the implementation of this kind of cool! Of course, no such opportunistic method is required!
The Code is as follows:
Package com. wenj. test;
Import javax. script. ScriptEngine;
Import javax. script. ScriptEngineManager;
/**
* Enter an expression with no parentheses and the number is smaller than 0-9. The calculation result is output. All intermediate results are converted into an integer.
Example: input: 3 + 8x2/9-2
Output: 2
Function prototype
Public int getMyRet (String str)
* @ Author wenj91-PC
*
*/
Public class TestCalcEq {
Public static void main (String args []) {
String strIn = "3 + 8x2/9-2 ";
TestCalcEq tc = new TestCalcEq ();
System. out. println (tc. getMyRet (strIn ));
}
Public int getMyRet (String strIn ){
String strTemp = strIn;
StrTemp = strTemp. replaceAll ("x", "*"); // convert x to the symbol used by the computer for multiplication *
StrTemp = strTemp. replaceAll ("X ","*");
ScriptEngineManager sMgr = new ScriptEngineManager ();
ScriptEngine sE = sMgr. getEngineByName ("js ");
Object result = null;
Try {
Result = (Object) sE. eval ("(" + strTemp + ")"); // directly call js eval to calculate the expression to get the result
} Catch (Exception e ){
}
Return (int) (double) result;
}
}