Hi I want to be able to find out the int (or float) value of a variable whoose name is in another string variable

int x = 10;
String var = "x";
System.out.println(Integer.valueOf(var).intValue());

I want 10 to be printed but all I get is :

Exception in thread "main" java.lang.NumberFormatException: For input string: "x"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.valueOf(Integer.java:553)
at Line2f.main(Line2f.java:57)

Can you help me?

from here

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
String expression = "n=10; n+4";
Object result = engine.eval(expression);
System.out.println(expression+" = "+result);
} catch(ScriptException se) {
se.printStackTrace();
}
}
}

Output :

n=10; n+4 = 14.0

but is it possible to do that without using a script language?

Use a map.

what do you mean by map?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.