Solve string var res="10+5+5+7";, var z should be equal its calculated value; then var s= should string of z; | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Solve string var res="10+5+5+7";, var z should be equal its calculated value; then var s= should string of z;

I am in mid of project, for first time writing a long calculating program, I want to solve string with number and operators, and gets a value then convert again in string;

18th Jun 2017, 3:14 PM
ASHISH PANDEY
ASHISH PANDEY - avatar
4 Answers
+ 2
In Java, parse(something) will cast (convert) the datatype to whatever you are parsing. Ex/ Integer.parseInt("5"); // Returns the int with a value of 5 eval() can lead to vulnerabilities since you are noew allowing the user to modify your code. Here's an example/ Lets say I have this: var clear = false; This variable keeps track of the players hp (pretend this is for a game). Now I take input from the user and evaluate it: var word = eval(prompt("Enter an expression quickly!")); Now instead of entering some math, I just enter: clear = true; Welp, now I've just modified a variable in the program, for all I know that could crash the program.
18th Jun 2017, 6:36 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
If this you are not taking input from the user an elegant way would be to use eval() var res = "10+5+5"; var z = eval(res); // calculated value eval(String) will evaluate whatever is in the String. However, If you are doing this with user input for a website, do not use eval(). As it will evaluate the String as if it were code, it will lead to website vulnerabilities. Although, If it's just for a fun project go ahead. If you don't use eval() one method would be to go through the String with a loop and evaluate each part one by one. So once you hit something like a '+' You evaluate whatever is to the left, and to the right of the plus until there are no more operators found in the String. Then if you want to go further you will need some operators taking priority over others. So, maybe first check for any '/' then '*' then '+' then '-'.
18th Jun 2017, 6:18 PM
Rrestoring faith
Rrestoring faith - avatar
0
thanx buddy #Rresroring Faith, am just making simple project to be display on institute PC for new commers, but why not use on web page, and what is parse(something like this) in java
18th Jun 2017, 6:22 PM
ASHISH PANDEY
ASHISH PANDEY - avatar
0
OK, thanks for your efforts to explain , #Rrestoring Faith.
18th Jun 2017, 6:50 PM
ASHISH PANDEY
ASHISH PANDEY - avatar