【发布时间】:2012-04-10 04:22:43
【问题描述】:
您能否在 while 循环中创建一行代码来创建一个新数组 AND 将 数组的名称 更改为while 循环的每次迭代?
例子:
int size = 10;
int name_count = 1;
while(size <= 100)
{
//name_count is changing the name of the array by calling it
// "array1", "array2", etc...
//I know this may not be correct code for changing the name of
// the array, but it is suppose to get the point across.
int[] array(name_count) = new int[size];
for (int i = 0; i <= size; i++)
{ /* Adding numbers to an array */ }
size = size + 5;
name_count++;
}
【问题讨论】:
-
为什么要在每次循环迭代时更改数组的名称?不确定是否了解其背后的逻辑。 :) 无论如何,您的代码实际上不会更改数组的名称——它会创建一个新数组,不包含任何旧数字。
-
我需要创建 19 个不同的数组,第一个数组包含 10 个有符号整数,每个数组的大小将增加 5,直到达到 100。因此,希望每次迭代都更改数组名称。
-
您是否正在尝试重新创建一个数据结构,例如 ArrayList,随着更多元素的添加,它的数组大小会在底层增加?您有两个可以使用的选项,可以更有效地解决您的问题。首先,只需提前创建所有数组。或者其次,每次增加 5 时,使用
size = oldsize + 5创建一个新数组并将旧值复制到新数组中。这样你的数组就会像 ArrayList 一样动态增长。
标签: java arrays variables while-loop iteration