能够在Java存储方法数组? [英] Can Java store methods in arrays?
问题描述
好吧,我写了一些code和所有我做的是循环的,但我叫更换哪种方法。我试图用一个for循环,以便它会有点整洁(和出于好奇,看看它是否可以做),但是当我这样做,这样它不会编译,因为它不承认在一个项目数组作为一种方法,我想。这是我有:
Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it'd be a bit neater (and out of curiosity to see if it could be done), but it doesn't compile when I do it this way, because it doesn't recognize an item in an array as a method, I think. This is what I have:
String[] moveArray = {moveRight,moveDown,moveLeft,moveUp};
for (i = 0; i < 4; i++) {
while (myWumpus.moveArray[i]) {
myWumpus.moveArray[i];
generator.updateDisplay();
}
}
当我尝试编译我收到
not a statement myWumpus.moveArray[i]();
';' expected myWumpus.moveArray[i]();
(它指的是在while循环的第一个语句)
(It refers to the first statement in the while loop)
所以,我认为这是可能是因为我让它成为一个String类型的数组?有没有一种方法类型?这是在所有可能的?任何解决方案,欢迎:)。另外,我可以得到它使用4 while循环,所以你不必告诉我,解决工作。谢谢!
So, I think it's maybe because I'm making it an Array of type String? Is there a type Method? Is this at all possible? Any solutions welcome :). Also, I can get it to work using 4 while loops, so you don't need to show me that solution. Thanks!
推荐答案
您不能储存方法直接在阵列。然而,你可以存储对象,不同的方式实现了同样的方法。例如:
You cannot store methods directly in arrays. However you can store objects, which implement the same method differently. For example:
Mover[] moveArray = {new RightMover(), new DownMover() new LeftMover(), new UpMover() };
for (i = 0; i < 4; i++) {
while (myWumpus.moveArray[i]) {
moveArray[i].move();
generator.updateDisplay();
}
}
这篇关于能够在Java存储方法数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!