How to make user input relate to a variable?

2019-03-03 22:37发布

问题:

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() ?

回答1:

Good solution

Don't make many variables like that.

You can put them all in an array :

Stack[] poles = new Stack[3];
for (int i=0; i<poles.length; i++) poles[i] = new Stack<Integer>();

Then you can access your poles using poles[yourInteger].

A variant (based on Jeffrey's comment) :

List<Stack<Integer>> poles = new ArrayList<Stack<Integer>>();
for (int i=0; i<poles.size(); i++) poles[i] = new Stack<Integer>();

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 :

public Stack<Integer> getPole(int i) {
    switch(myInteger) {
    case 1:
        return pole1;
    case 2:
        return pole2;
    case 3:
        return pole3
    }
    return null;
}

use it with

Stack<Integer> pole = getPole(yourInteger);

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 :

Field stackField = MyClass.class.getField("pole"+myInteger);

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.