[英]for each loop inside foreach loop?
This gives error. 这给出了错误。 Any other method to extract elements from a multi dimensional array one by one ?
从一个多维数组中逐个提取元素的任何其他方法?
I thought that for a foreach loop(variable holding corresponding value : array/Iterable), it is possible to first get the one dimensional array from a multiD. 我认为对于foreach循环(变量持有相应的值:array / Iterable),可以首先从multiD获取一维数组。 array and then create another foreach loop that extract elements from that array.
然后创建另一个foreach循环,从该数组中提取元素。 But it gives all sorts of errors in foreach loop.
但它在foreach循环中给出了各种错误。
1st error: Array2D.java:14: error: not a statement for(a : arr[] ) 第一个错误:Array2D.java:14:错误:不是(a:arr [])的声明
Code Behind: 代码背后:
class Array2D {
public static void main(String[] args) {
int[][] array = new int[][]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int a[] = new int[3];
for(a : array) {
for(int n : a) {
System.out.print(n + " ");
}
}
}
}
You need to change the first for
statement. 您需要更改第一个
for
语句。 Also, you must move the int[] a
declaration: 此外,您必须移动
int[] a
声明:
for(int[] a : arr) {
...
}
C# supports the following arrays: C#支持以下数组:
Examples: 例子:
int[] numbers; // Single-dimensional arrays // 1
string[,] names; // Multidimensional arrays // 2
int[][] detail; // jagged arrays // 3
It is worthy to note that in C# arrays are objects and must be instantiated. 值得注意的是,C#数组是对象,必须实例化。
So, instantiation for the above samples might look like: 因此,上述示例的实例化可能如下所示:
int[] numbers = new int[5]; // 1
string[,] names = new string[5,4]; // 2
int[][] detail = new int[7][]; // 3
for (int d = 0; d < detail.Length; d++)
{
detail[d] = new int[10];
}
As to your sample, it might be rewritten to the following way: 对于您的示例,可能会按以下方式重写:
static void Main(string[] args)
{
int[][] arr = new int [][]
{
new int[] {1,2,3},
new int[] {4,5,6},
new int[] {7,8,9}
};
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j] + " ");
}
System.Console.WriteLine();
}
}
With Java, I think it will look like 使用Java,我认为它看起来像
for(int[] arr : array)
{
for(int n : arr)
{
System.out.print(n + " ");
}
}
I would try: 我会尝试:
for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[r].length; c++) {
// c and r are the indexes into the array
}
}
which gives you the indexes of the array element by iterating across the length of each array/array row. 它通过迭代每个数组/数组行的长度为您提供数组元素的索引。
Or if you just need the elements without the indexes 或者,如果您只需要没有索引的元素
for (int[] a : arr) {
for (int b : a) {
// gives you the element in b
}
}
In the first for put: 在第一次投入:
for(a : arr) {
//
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.