I don't know how to phrase this question precisely, but this is what I want to achieve (I am implementing the Towers of Hanoi illustration using stacks:
This is inside the main()
function:
System.out.println("Type the source pole number and the destination pole number");
int a = reader.nextInt();
int b = reader.nextInt();
boolean move = moveDics(a, b);
These are the stacks which represent the 3 poles:
Stack<Integer> pole1 = new Stack<Integer>();
Stack<Integer> pole2 = new Stack<Integer>();
Stack<Integer> pole3 = new Stack<Integer>();
I want to change the stacks based on the user input, and to do so I need to related to the variables pole1, pole2, pole3 (to preform any action, like pole1.pop()
).
And this is my question: how can I user the user input - an integer - to relate to the poles, other than multiple if() statements or a switch case statement? Something like pole + "x".pop()
?
Good solution
Don't make many variables like that.
You can put them all in an array :
Then you can access your poles using
poles[yourInteger]
.A variant (based on Jeffrey's comment) :
Then you can access your poles using
poles.get(yourInteger)
.Note that as soon as you start to do more complex things on those poles, you'd have to consider embedding them in a class. I personally try to avoid collections of collections or arrays of collections as they tend to be confusing.
Not very good solution
You may use a switch :
use it with
Crazy solution
You may, if you want, access your variables by name using reflexion.
To do this, you first fetch the Field instances of your class :
Then you have to get the methods of this field's value, and call them. This will be slow, many LOC and many try/catch.