-3

I want to make the user able to name a String variable at runtime.

Scanner input = new Scanner(System.in);
String name = input.nextLine();

The program asks me to type a word. How can I then create a variable whose identifier is the user's input?

I have tried this:

String (name) = "blah";

But it does not work.

mgthomas99
  • 5,402
  • 3
  • 19
  • 21

3 Answers3

2

You can use a Map

String input1 = ...;
String input2 = ...;
Map m = new HashMap<String,String>();
m.put(input1, input2);
Rahul
  • 76,197
  • 13
  • 71
  • 125
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

This does not work in java, cause variable names are "gone" during runtime. The compiled version does no longer use them.

In PHP it is possible, because PHP is interpreted during runtime.

The "closest" you can get is the usage of a hashmap:

Map<String,String> kvps = new HashMap<String,String>();
kvps.put ("varname", "varvalue");
kvps.put ("hello", "world");
kvps.put ("foo", "bar");

for (Map.Entry<String, String> kvp: kvps.getEntrySet()){
  System.out.println(kvp.getKey() + " = " + kvp.getValue());
}
dognose
  • 20,360
  • 9
  • 61
  • 107
0

There is a way you can get a name of a variable - if it is a field of a class, then you can use reflection:

Field[] classFields = classInstance.getDeclaredFields();

Now you can get the field names:

classFields[index].getName();
mgthomas99
  • 5,402
  • 3
  • 19
  • 21
user265732
  • 585
  • 4
  • 14