Shashi Ranjan
Shashi Ranjan

Reputation: 1561

Use String values as variables

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?

Upvotes: 2

Views: 354

Answers (5)

Ross Drew
Ross Drew

Reputation: 8246

  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.

Upvotes: 0

monk
monk

Reputation: 228

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);

Upvotes: -1

Neha
Neha

Reputation: 1548

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) {

        }

Upvotes: 1

Tu Tran
Tu Tran

Reputation: 1977

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.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

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.

Upvotes: 1

Related Questions