简体   繁体   中英

Getting the user to name the variables

For my program i want to have it so that the user can name the variables a bit like in a game you would name your charecter/world. I looked it up and couldn't find anywhere that said if this is possible and if so how it is done.

What you can do is create a linked list or an arraylist of some type of object that you create. Your object can then have two properties (or more) where one is the name, and the other is the value. You can then search for an object in your list based on the name, and return the value that you want. This will basically accomplish what you're trying to achieve.

As many others have said, you can't dynamically name variables.

You can however make a Map

It would allow you to create any name for a variable such as "MyTestVar" at runtime and use it as a key in that map to whatever you put:

Map<String, String> myMap = new HashMap<String, String>();

String varName = getVariableNameFromUser();
String value = getValueFromUser();

myMap.put(varName, value);


// ... later


String whatVariableDoYouWantTheValueOf = getVarNameFromUser();
String storedValue =  myMap.get(whatVariableDoYouWantTheValueOf);
System.out.println("The value for that is: " + storedValue);

You can't get a user to name a variable. All you can do is allow the user to set the variable's value.

I guess what you mean is something like giving Tags or Labels to Objects. "Variable Names" is a missleading wording for that.

After the User typed in the name string for an obj Object, you could for example use a HashMap<String, Object> to store the user input:

Map<String, Object> tagToObjectStore = new HashMap<String, Object>();

String userInput = "any Tag name";
Object somethingToLabel = ... // TODO

tagToObjectStore.put(userInput, somethingToLabel); // store the user input

// later in code...

Object theStoredObject = tagToObjectStore.get(userInput); // get the stored object

Is that what you are looking for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM