我不知道如何准确地表达这个问题,但这就是我想要实现的目标
(我正在使用堆栈实现河内塔插图:
这是里面的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 个极点的堆栈:
Stack<Integer> pole1 = new Stack<Integer>();
Stack<Integer> pole2 = new Stack<Integer>();
Stack<Integer> pole3 = new Stack<Integer>();
我想根据用户输入更改堆栈,为此我需要与变量 poll1、pol2、pol3 相关(以执行任何操作,例如pole1.pop()
).
这是我的问题:除了多个 if() 语句或 switch case 语句之外,如何使用用户输入(整数)来与极点相关?就像是pole + "x".pop()
?
好的解决方案
不要像这样设置很多变量。
您可以将它们全部放入一个数组中:
Stack[] poles = new Stack[3];
for (int i=0; i<poles.length; i++) poles[i] = new Stack<Integer>();
然后你可以使用你的杆子poles[yourInteger]
.
一个变体(基于杰弗里的评论):
List<Stack<Integer>> poles = new ArrayList<Stack<Integer>>();
for (int i=0; i<poles.size(); i++) poles[i] = new Stack<Integer>();
然后你可以使用你的杆子poles.get(yourInteger)
.
请注意,一旦您开始在这些杆上做更复杂的事情,您就必须考虑将它们嵌入到类中。我个人尽量避免使用集合的集合或集合的数组,因为它们往往会令人困惑。
不是很好的解决方案
您可以使用开关:
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);
疯狂的解决方案
如果需要,您可以使用反射按名称访问变量。
为此,您首先获取类的 Field 实例:
Field stackField = MyClass.class.getField("pole"+myInteger);
然后你必须获取该字段值的方法,并调用它们。这会很慢,有很多 LOC 和很多 try/catch。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)