I have 2 objects called X and Y created from a class called Product which has a field called numInStock.

From another driver program, I want a user to input either X or Y with their response being stored in a string userchoice (so user enters X or Y as a response)

Then I want to be able to use the value of userchoice to retrieve the number of items in stock.

so I want the userchoice string in userchoice.numInStock to somehow be replaced by the object chosen by the user.

I guessed Product.getName(userchoice).numInStock, along with 20 other wildguesses, but can't stuble on something that works.
Please, is there a simple way to do this?

6 Years
Discussion Span
Last Post by IsharaComix

Have you tried using a Map? It might be overkill for your problem, but this fits your query pretty well, and is scalable to larger cases. This will allow you to pass in a string to fetch a named object, and also stores them in a nice space too.

TreeMap<String, Product> map = new TreeMap<String, Product>();
map.put( "X", new Product() );
map.put( "Y", new Product() );

Now you can use map.get(user_input) to get the proper Product, which you can then check for whatever parameters you want. If the object isn't in the map, then it will just return a value of null.

More info: http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.