假设我想根据计数在循环内声明一定数量的变量。
private static void declaration(int amount)
{
for (int i = 0; i <= amount; i++)
{
/*Code that declares variables.
*
*When i == 0, it will declare int num0 with a value of 0.
*When i == 1, it will declare int num1 with a value of 0, etc.
*/
}
}
这可以在Java内部进行吗?
答案 0 :(得分:0)
不是这样,你需要某种数据结构,例如:列表,地图等。
e.g。如果需要通过名称识别
Map<String, Integer> variables = new HashMap<String, Integer>();
for (int i = 0; i <= amount; i++) {
variables.put("num" + i, 0);
}
// latter get value
System.out.println(variables.get("num3"));
e.g。如果只有索引重要
int[] state = new int[amount];
for (int i = 0; i <= amount; i++) {
state[i] = 0; // <== all elements are already zero, but just to show you idea
}