如何使用户输入与变量相关? [英] How to make user input relate to a variable?

查看:65
本文介绍了如何使用户输入与变量相关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道该如何精确地表达这个问题,但这是我想要实现的目标(我正在使用堆栈来实现河内塔的插图:

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:

这是在 main()函数内部:

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);

这些是代表3个极点的堆栈:

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

我想根据用户输入来更改堆栈,为此,我需要与变量pole1,pole2,pole3相关联(执行任何操作,例如 pole1.pop()).

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

这是我的问题:除了多个if()语句或switch case语句之外,如何使用用户输入-一个整数-与极点相关?像 pole +"x" .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() ?

推荐答案

好的解决方案

不要那样做很多变量.

您可以将它们全部放在一个数组中:

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

然后,您可以使用 poles [yourInteger] 访问您的两极.

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

然后,您可以使用 poles.get(yourInteger)访问极点.

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.

不是很好的解决方案

您可以使用开关:

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

Stack<Integer> pole = getPole(yourInteger);

疯狂的解决方案

如果需要,可以使用反射通过名称访问变量.

You may, if you want, access your variables by name using reflexion.

为此,您首先要获取类的Field实例:

To do this, you first fetch the Field instances of your class :

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

然后,您必须获取该字段值的方法,然后调用它们.这会很慢,很多LOC和很多try/catch.

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.

这篇关于如何使用户输入与变量相关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆