How to make user input relate to a variable?

血红的双手。 提交于 2020-01-11 13:15:50

问题


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.



来源:https://stackoverflow.com/questions/11560768/how-to-make-user-input-relate-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!