2

I have a situation to use String values as variables, Like:

int val1;
int val2;
String s = "val1*val2";

Now I have to get output like:

int output = (value which is calculated in s);

How can I achieve this?

psxls
  • 6,807
  • 6
  • 30
  • 50
Shashi Ranjan
  • 1,491
  • 6
  • 27
  • 52
  • 1
    possible duplicate of [Evaluating a math expression given in string form](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – neutrino Dec 04 '13 at 09:19
  • 2
    didn't get your problem .. could you please explain a bit more ? – A N M Bazlur Rahman Dec 04 '13 at 09:19
  • use type casting methods – thar45 Dec 04 '13 at 09:20
  • This is not a duplicate of that other question at all. That other question had numbers and operators in the expression. This one has variable names too, which makes it quite different. Perhaps the people who have voted to close could reconsider. – Dawood ibn Kareem Dec 04 '13 at 10:16

5 Answers5

1

Your question is not quite clear. But you may try as follows

 String s = String.valueOf(val1*val2);

Then

 int output = Integer.parseInt(s);

If you mean to get value by name. you can try with Java-reflection.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • 1
    He is looking to get the variable name from a string first, then get it's value. This just calculates it and stores it in String form – Ross Drew Dec 04 '13 at 09:24
1

Try this its gives you expected o/p but you have to handle reflection exception and take care that val1/val2 are int. its just format sample.

    class a {
            public int val1 =2;
            public int val2 = 3;
            public String s = "val1*val2";
            public int val = 0;
        }           
        a a1 = new a();
        StringTokenizer str = new StringTokenizer(a1.s,"*");
        try {
            a1.val = (int) a1.getClass().getField(str.nextToken()).get(a1) * (int)   
                     a1.getClass().getField(str.nextToken()).get(a1);

                      System.out.println("v=" +a1.val);
        } catch (Exception e1) {

        }
Neha
  • 1,548
  • 2
  • 10
  • 13
  • This would only work for multiplication and is a very complicated way of doing Reflection (especially with no explanation). Catching `Exception` is also a bad idea. – Ross Drew Dec 04 '13 at 09:43
  • 1
    this is only to solve the mention issue, and exception need to handle.. i kind of left to user, about multiply -- can add switch case base on operator anyway either they check a1.s.contains(operator) and than switch case it. – Neha Dec 04 '13 at 09:47
  • Actually the problem here is I don't know what is the math calculation on those variable. It might be addition, division etc or any math. I am getting this string from excel sheet. – Shashi Ranjan Dec 04 '13 at 09:58
  • +1. This answer shows how to solve the problem. There's no point in showing all the available math operations (except perhaps to demonstrate order of operations). – Dawood ibn Kareem Dec 04 '13 at 10:19
  • @Shashi as i suggest in comment make the string list of operator like String [] opt = {"%", "*", "+" ,"-" ..} (it should be limited to standard math operator so you can define them) loop through the a1.s.contains(opt[i]) and take out the operator string use it in Stringtokenzier and make switch case for calculation. – Neha Dec 05 '13 at 04:23
0
  1. You would first need to parse out the different elements (variable names and special characters). That is either uses a StringTokeniser to extract each element or iterate over the String and extract separate strings for variables or symbols.
  2. then you would need something called Reflection to get the variables and their values from their string name

    //Reflection example
    Field tmpField = yourClassInstance.getClass().getField("val1");      
    System.out.println(tmpField.get(yourClassInstance)); // this prints the value of val1
    
  3. then lastly use the parsed out special symbols and do your math on them.

Community
  • 1
  • 1
Ross Drew
  • 8,163
  • 2
  • 41
  • 53
  • what is "yourClassInstance" here? – Shashi Ranjan Dec 04 '13 at 09:29
  • The instance of the class that your `val1` and `val2` are contained in. So if they are inside a class called `MyClass` and you create one with `MyClass myClass = new MyClass()` then yourClassInstance is `myClass` – Ross Drew Dec 04 '13 at 09:30
  • 1
    Yes this is the one which I wanted. But what about string calculation thing? – Shashi Ranjan Dec 04 '13 at 09:44
  • Actually the problem here is I don't know what is the math calculation on those variable. It might be addition, division etc or any math. I am getting this string from excel sheet. – Shashi Ranjan Dec 04 '13 at 09:56
  • The example I've given just extracts the variable names and provides their values. The link titled 'do your math' answers the question of extracting mathematical symbols and using their operations. I've also updated the answer to be more detailed. – Ross Drew Dec 04 '13 at 09:58
  • 1
    The example there in operates math on constant values not on variable. – Shashi Ranjan Dec 04 '13 at 10:15
  • Yes and my code expands that so that you can retrieve the variable. Together they answer the question. – Ross Drew Dec 04 '13 at 10:18
0

I think that you want to write a dynamic method which calculate something given by a string. If so, please refer article

I prefer the first method, which can evaluate everything as an java application.

Tu Tran
  • 1,957
  • 1
  • 27
  • 50
-1

this maybe work

    String s="20*12";
    String opReg="\\D";
    Pattern opp=Pattern.compile(opReg);
    Matcher m = opp.matcher(s);
    int output=0;
    if(m.find()){
        String op=m.group();
        String[] vars=s.split(opReg);
        int var1=Integer.valueOf(vars[0]),
                var2=Integer.valueOf(vars[1]);
        System.out.println(op);
        switch(op.charAt(0)){
        case '*':
            output=var1*var2;
            break;
        case '/':
            output=var1/var2;
            break;
        case '+':
            output=var1+var2;
            break;
        case '-':
            output=var1-var2;
            break;
        }
    }
    System.out.println(output);
monk
  • 228
  • 2
  • 10