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?

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

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.