java 遍历具有通用名称的变量

java Loop through variables with a common name

我正在尝试用随机数创建 10 个变量,所有变量都以同一个词开头,例如:
- Foo1
- Foo2
- Foo3
- Foo4

我正在尝试的是:

for(int i = 0; i < 20; i += i){
  int name = int("Foo" + i)
  name = random(100, 500);
  image(blabla, blabla, name);  //the blabla are fixed coordinates
};


但是我无法让它工作。
你们知道怎么解决吗?

提前致谢!

如果你想以编程方式访问一个变量,你必须使用反射,但是对于任何人来说这都不是一个好的解决方案,除了有经验的程序员设计高级 API。 您应该为变量使用 ArrayList。

你可以使用数组。

数组是一个包含多个值的变量。

int[] r = {1, 2, 3};
int x = r[0];

Here 是处理数组引用。

在您的示例中,您可以这样做:

PImage[] images = new PImage[20];
images[0] = loadImage(...);
//..load rest of images

for(int i = 0; i < 20; i += i){
  image(blabla, blabla, images[i]);
}

您可能还想查看 ArrayList or HashMap 类。

您可以使用地图。例如

Map<String, Integer> vars = new HashMap<String, Integer>();

for(int i = 0; i < 10; i ++)
    vars.put("Foo" + i, (int) Math.round(Math.random() * 500) + 100);

System.out.println(vars.get("Foo8")); // Accessing to Foo8 value