Getting the user to name the variables - java

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.

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);

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.

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?

Related

Make a registry/database list in Java

I wonder how to make a registry/database list in Java. I mean if I, for example, have a variable called "data", and then I add a new entry to that called "name" with the value "David". Then I would call something like "data.name" to get the value "David".
As seen on this picture
I've been Googling but not finding anything about it.
It sounds like you want a Map from String to String. You can use a HashMap<String,String> for that.
// Create Map using HashMap
Map<String, String> data = new HashMap<String, String>();
// Set name
data.put("name", "David");
// Get name
String name = data.get("name");
System.out.println(name);

Naming java objects

So right now, I am making a simple java banking program. It allows you to add a customer and deposit/withdraw funds. Right now, I have 3 classes: Main, Bank, and Customer. Right now I have it so that when you add a customer, it asks you for a name. But right now I am having trouble naming them. I want
Customer to have a username as the object name. For example, if I typed in Bob1789 as the username, the program would do:
Customer Bob1789 = new Customer("Bob1789");
If I typed in randomcustomer123 the program would do:
Customer randomcustomer123 = new Customer("randomcustomer123");
So basically, whatever I type in the box from the scanner, to be passed to the Customer name.
Customer (whatever was typed in the scanner) = new Customer((whatever was typed in the scanner));
I have tried to do this, but java always assumes that the scanner.NextLine() is the Object name.
Is there any way to do this?
You can use a HashMap<String, Customer> for this. This allows you to store name-customer pairs.
HashMap<String, Customer> allCustomers = new HashMap<>();
To create a new customer and put it into the map,
String customerName = scanner.nextLine();
allCustomers.put(customerName, new Customer(customerName));
To get a customer with a specific name, use this:
allCustomers.get("some name");
Don't know why you want to use obj name. Probably you need to use HashMap<String, Customer> where name is the key and value is the object.
Map<String, Customer> map = new HashMap<>();
to add map.put("yourName", obj);
to fetch map.pget("yourName");

How to get values from inner object in the hashmap in java?

I have a HashMap. Object contains info like name, address, email. I am able to iterate HashMap but not able to get values from the Object. Here is my code if anyone can please show me a proper way to do this.
public void getData(){
// hashmap is records<key, Object>
// Object contains properties name, address, email
Iterator it = records.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object val = entry.getValue();
// this gets me through hashmap
// how do I get name, address and email from object?
}
}
Since you are not using generics, you will need to explicitly cast the result of entry.getValue() to the class of the object with name, address, and email.
You didn't provide that actual class, but it might be something like:
Person val = Person.class.cast(entry.getValue());
name = val.getName();
// and so on....
You cannot simply get the item by calling .getValue(). You need to assign the object to whatever object type you're using. You shouldn't simply cast, because that will only satisfy syntactical constraints by java's compiler. You want to make sure that your object is indeed what you think it is. For example:
Object o = it.next();
if (o instanceof MyObjType)
{
MyObjType obj = (MyObjType) o.
}
Lets say your name, address, email is in a object of type PersonalInfo. Then when you define your iterator use generics as follows -
Iterator<PersonalInfo> it = records.entrySet().iterator();
You can also define your Map that way. No need to use Object as you know the date or object that the Object(Polymorphic reference) will hold.
Do define your Map like -
Map<key, PersonalInfo> records = new HashMap<key, PersonalInfo>();
Inside your PersonalInfo class you will have getter and setter methods for each variable like name,email etc.Now you can extract data as follows -
PersonalInfo myInfo = entry.getValue();
String name = myInfo.getName();
String email = myInfo.getEmail();
//etc...

Can you reference a java variable from a string?

Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.

Using one variable as an another variable of different data type but the same name

I am using a class where I am taking input as the file name and the file location. I have a pre defined file names, so I will match the predefined file names with the file name that I received and then store the values accordingly. Please look at the code below
//Set of storage maps and tables
public class storage
{
//Storage set
public static Set<Integer> tiger = new HashSet<Integer>();
//Storage set
public static Set<Integer> lion = new HashSet<Integer>();
//This is the table used for storing the browser customer count
public static Table<String,String,Integer> elephant = HashBasedTable.create();
//Storage map
public static Map<String, String> monkey = new HashMap<String, String>();
public static void storeDataDirector(String fileLocation,String fileName) throws Exception
{
if (fileName = monkey)
**update the "monkey map"**
}
This is my problem, also I have lot of maps and tables to be used so I wouldn't be able to use multiple if conditions and then check and update the same.
What I would like to know is the below
As I have said earlier, The file name that I am sending to the program which is "String filename" has the same name of the "Map monkey" but the former is a String and the latter is the map. I would like to know if I will be able to use the string variable as a reference to the map instance as both of them have the same name . This will highly avoid the if conditions that I am using in the program and thus I would like to possible solution for this ... Anything related to type caseting ort
You need to have another Map - whose key is a String and value is a Map. Something like Map<String,Map> allMaps = new HashMap<String,Map>()
Once you have this map , populate it with all your filenames and the corresponding maps monkey.
allMaps .put("monkey", monkey)
If a string filename corresponds to not a map but to a set , then you need to declare something more general Map<String,Object> allMaps = new HashMap<String,Object>(). Ofcourse this means you need to cast the value to its particular type before you can do any meaningful thing with it.
Then , to use this map , use your filename argument
Map monkeyAgain = allMaps.get(filename)
You can use reflection:
Storage.class.getField(fileName).get(null)
You will still have to cast the returned object. I do not think this the right approach.
The idea is to relate them in a Map, and use the file name as a key for example
Map<String, Map<String, String>>
// file store structure
If you need a generic solution, you could solve this by implementing an abstraction of your store structure, by implementing an interface similar to this one:
// T is the store type and U is the original type (String from file for instance...)
public interface StoreUnit<T, U> {
void update(U record);
List<T> list();
}
so you will have an implementation for each case (Set, Map, Table ...) and will relate it in a map using the file name as key.
monkeyFileName => MapStoreUnit<Entry<String,String>,String>
tigerFileName => SetStoreUnit<Integer, String>
elephantFileName => TableStoreUnit<Entry<Entry<String,String>,String>,String> // not sure if for Table there is something better than Entry ;)
When you wanna update some store you perform a get over the map using the file name as key, and invoking update method implemented with the record (that could be an String, complex Object) and so on. When you need to read something from there you could use the list method.

Categories