gpt4 book ai didi

Java 数组创建和数组名称更改

转载 作者:行者123 更新时间:2023-12-02 07:54:01 24 4
gpt4 key购买 nike

你能在 while 循环中创建一行代码来创建一个新数组并且更改数组的名称 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++;
}

最佳答案

标识符名称需要在编译时定义。因此,您不能在循环的每次迭代中显式使用不同的变量名称。

伪代码的另一个问题是,如果要在循环内声明数组,则当循环完成时它将超出范围,因此没有太多意义。

要做这样的事情,您需要使用一些集合来保存数组,并且将它们设为显式对象而不仅仅是数组会更容易。像这样的东西:

List<List<Integer>> listOfArrays = new ArrayList<List<Integer>>();
while (size <= 100) {
List<Integer> listOfNumbers = new ArrayList<Integer>(size);
/* insert loop here to add numbers to listOfNumber */

size += 5;
name_count += 1;
}

然后,您可以使用 listOfArrays 中的索引来访问每个数字列表 - 相当于使用索引命名每个数字,但在运行时而不是编译时处理。

关于Java 数组创建和数组名称更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9875952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com