-1

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.

pradeep cs
  • 513
  • 4
  • 9
  • 34

5 Answers5

7

Use an array:

 String[] q = {q1, q2, q3, q4, q5};
 for (String s : q) 
    System.out.println(s);
Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
  • I second this answer, but honestly, the user is not clear on his/her intentions. Are you trying to concatenate a string, turn a string representation of an integer into a integer then add it with i... – Andy Apr 09 '12 at 18:52
  • this does seem like what the user wants – Kevin Apr 09 '12 at 19:03
1

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.

Community
  • 1
  • 1
James C
  • 21
  • 3
0

You can use java reflection to check defined fields in class.

for example Class.getField(String)

viliam
  • 503
  • 6
  • 23
0

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.

MarioDS
  • 12,895
  • 15
  • 65
  • 121
0

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.

Community
  • 1
  • 1
Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82