gpt4 book ai didi

java - 在java中使用增强的for循环初始化多维数组

转载 作者:行者123 更新时间:2023-12-01 17:03:39 25 4
gpt4 key购买 nike

我只是在摆弄我的代码,想知道是否可以使用增强的 for 循环初始化多维数组。

如何解决这个问题?

double[][] array2 = new double[2][5];
int b=1;
counter=0;
for(double[] x:array2)
{
for(double a:x)
{
array2[][counter]=b; //<- errors here
counter++;
b+=2;
}
}

//output what it contains
for(double[] x:array2)
{
for(double a:x)
{
System.out.println(a);
}
}

你们会如何用 3 维来做到这一点?

  double[][][] array3 = new double[4][5][6];

我知道我可以使用集合来做这些事情,但我只是在尝试。

最佳答案

由于您需要一个索引来写入数组,因此无法使用增强的 for 循环进行更新。但是,对于 Java 中的多维数组,您仅修改最里面的数组。因此,您可以对外部数组使用增强的 for 循环:

double[][] array2 = new double[2][5];
int b=1;
for(double[] x:array2) {
for(int index = 0; index < x.length; index++) {
x[index]=b;
b+=2;
}
}

这同样适用于任意数量的维度:

double[][][] array3 = new double[4][5][6];
int b=1;
for(double[][] outer: array3)
for(double[] inner: outer)
for(int index = 0; index < inner.length; index++) {
inner[index]=b;
b+=2;
}

关于java - 在java中使用增强的for循环初始化多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26484736/

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