How to evaluate the java variables? I have few strings String q1,q2,q3,q4,q5
for(i=1;i1<=5;i++){
//evaluate the value of q1,q2,q3,q4,q5
system.out.println(q+i); //should print q1,q2,q3,q4,q5 values concurrently
}
Please help me.
How to evaluate the java variables? I have few strings String q1,q2,q3,q4,q5
for(i=1;i1<=5;i++){
//evaluate the value of q1,q2,q3,q4,q5
system.out.println(q+i); //should print q1,q2,q3,q4,q5 values concurrently
}
Please help me.
Use an array:
String[] q = {q1, q2, q3, q4, q5};
for (String s : q)
System.out.println(s);
I believe he is referring to the eval function from flash's actionscript and javascript.
With it you can do things like
for (i = 1; i <= 4; i++){
eval("func" + i + "( )");
}
Which would call func1(), func2(), func3(), func4(). Similarly you could do this with string variables.
You can not do this in Java and if you feel you must print these separate variables with a for loop then your best bet is Eugene's answer of putting them in an array first.
edit: I was typing my answer and did not notice Ravinder's answer. Thanks for that reference. I have never used ScriptEngine before and will have to check it out.
You can use java reflection to check defined fields in class.
for example Class.getField(String)
This code doesn't compile, what you try to print there is the value of a variable q, incremented with the value of i. There is no q, and you don't want the value of i.
Use Eugene Retunsky's solution instead.
It seems you are trying to find a Java
equivalent of eval
function in JavaScript
.
If yes, answers at using eval in Java may be helpful to you.