How to Perform Arithmetic on Values and Operators Expressed as Strings

How to perform arithmetic on values and operators expressed as strings?

Here are some alternatives:

1) read.table Read the text in as if it were a file and then divide:

with(read.table(text = x, sep = "/"), 100 * V1 / V2)
## [1] 66.66667 83.33333 27.27273

2) eval/parse eval/parse is generally frowned upon but here is how it would work:

100 * sapply(as.list(parse(text = x)), eval)
## [1] 66.66667 83.33333 27.27273

3) strsplit

sapply(strsplit(x, "/"), function(x) { x <- as.numeric(x); 100 * x[1] / x[2]})
## [1] 66.66667 83.33333 27.27273

4) gsubfn::strapply This picks out the two strings of digits using strapply and then converts each to numeric and divides:

library(gsubfn)

strapply(x, "(\\d+)/(\\d+)", ~ 100 * as.numeric(x) / as.numeric(y), simplify = TRUE)
## [1] 66.66667 83.33333 27.27273

Perform arithmetic operations from operators defined as strings

Starting from JDK1.6 you can use built-in Javascript engine to evaluate this expression for you .

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Main {
public static void main(String[] args) throws Exception{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String expression = "100+200/100*2";
System.out.println(engine.eval(expression));
}
}

So you can use it to calculate the expression according to operators precedence rules.

Also If you need just the count of solutions , it might be easier to use TreeSet then print the size of the set at the end.

Here is a full explanation :

public class Main {

public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
int a = 100;
int b = 200;
int c = 300;
int d = 100;
String[] chars = {"+", "-", "*", "/"};
try {
TreeSet<String> set = new TreeSet<>();
for (int i=0; i<chars.length; i++){
for (int j=0; j<chars.length; j++){
for (int k=0; k<chars.length; k++){
String expression = a+chars[i]+b+chars[j]+c+chars[k]+d;
set.add(String.valueOf(engine.eval(expression)));
}
}
}
System.out.println(set.size());
} catch (ScriptException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

trying to perform arithmetic operations on numbers expressed as a character string

I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.

That is the right idea. I suggest that you stop looking at the code that you found. (I'm sure that your teachers don't want you to look up the answers on the internet, and you will learn more from your homework if you don't do it.)

So how to proceed?

(I am assuming that you are supposed to code the methods to do the arithmetic, and not just convert the entire string to a primitive number or BigInteger and use them to do the arithmetic.)

Here's my suggested approach:

  1. What you are trying to program is the equivalent of doing long addition with a pencil and paper. Like you were taught in primary school. So I suggest that you think of that pencil-and-paper procedure as an algorithm and work out how to express it as Java code. The first step is to make sure that you have the steps of this algorithm clearly in your head.

  2. Try to break the larger problem into smaller sub-problems. One sub-problem could be how to convert a character representing a decimal digit into an integer; e.g. how to convert '1' to 1. Next sub-problem is adding two numbers in the range 0 to 9 and dealing with the "carry". A final sub-problem is converting an integer in the range 0 to 9 into the corresponding character.

    Write sample Java code fragments for each sub-problem. If you have been taught about writing methods, some of the code fragments could be expressed as Java methods.

  3. Then you assemble the solutions to the sub-problems into a solution for the entire problem. For example, adding two (positive!) numbers represented as strings involves looping over the digits, starting at the "right hand" end.

  4. As part of your program, write a collection of test cases that you can use to automate the checking. For example:

      String test1 = add("8", "3");
    if (!test1.equals("11")) {
    System.out.println("test1 incorrect: expected '11' go '" +
    test1 + "'");
    }

Hints:

  • You can "explode" a String to a char[] using the toCharArray method. Or you could use charAt to get characters individually.

  • You can convert between a char representing a digit and an int using Character methods or with some simple arithmetic.

  • You can use + to concatenate a string and a character, or a character and a string. Or you can use a StringBuilder.

  • If you need to deal with signed numbers, strip off and remember the sign, do the appropriate computation, and put it back; e.g. "-123 + -456" is "- (123 + 456)".

  • If you need to do long multiplication and long division, you can build them up from long addition and long subtraction.

Arithmetic operations on string value

This can be achieved with infix to postfix expression evaluation , you can read more this on http://faculty.cs.niu.edu/~hutchins/csci241/eval.htm

Performing math operation when operator is stored in a string

I don't recommend this but is funny. in java6

String op = '+';
int first= 10;
int second = 20;
ScriptEngineManager scm = new ScriptEngineManager();
ScriptEngine jsEngine = scm.getEngineByName("JavaScript");
Integer result = (Integer) jsEngine.eval(first+op+second);

go with the switch, but remember to convert the string operator to char as switch don't works with strings yet.

switch(op.charAt(0)){
case '+':
return first + second;
break;
// and so on..

how to use the a string value for arithmetic equations?

I think best option for you is switch case, see this example code:

int result;

switch (operator)
{
case "+":
result = value1 + value2;
break;
case "-":
result = value1 - value2;
break;
case "*":
result = value1 * value2;
break;
case "/":
//check if value2 is 0 to handle divide by zero exception
if(value2 != 0)
result = value1 / value2;
else
System.out.println("DIVISION NOT POSSIBLE");

break;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);

}

return result;

And in this case the default case will replace the first If check and you will be able to remove it.

operators as strings

The way I see it, you have two options - use an expression evaluator or construct, compile
and run C# code on the fly.

I would go with an expression evaluator library, as you do not have to worry about any security issues. That is, you might not be able to use code generation in medium trust environments, such as most shared hosting servers.

Here is an example for generating code to evaluate expressions:
http://www.vbforums.com/showthread.php?t=397264

How to do math operations with string?

You could write something like:

def parse_exp(s):
return eval(s.replace('x','*'))

and expand for whatever other exotic symbols you want to use.

To limit the risks of eval you can also eliminate bad characters:

import string

good = string.digits + '()/*+-x'

def parse_exp(s):
s2 = ''.join([i for i in s if i in good])
return eval(s2.replace('x','*'))

Edit: additional bonus is that the in-built eval function will take care of things like parenthesis and general calculation rules :)

Edit 2: As another user pointed out, evalcan be dangerous. As such, only use it if your code will ever only run locally



Related Topics



Leave a reply



Submit