How to make user input relate to a variable?

前端 未结 1 360
长发绾君心
长发绾君心 2021-01-27 07:45

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

相关标签:
1条回答
  • 2021-01-27 08:14

    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.

    0 讨论(0)
提交回复
热议问题