对于使用二维数组的每个循环 [英] For each loop using 2D array

查看:24
本文介绍了对于使用二维数组的每个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Java代码片段:

int[][] uu = new int[1][1];uu[0][0] = 5;for(int[] u: uu){System.out.println(u[0]);}

打印出5.但是为什么for循环的声明部分声明为as int[] u,而不是as int[][] u?>

在 uu 处,您引用了 2D 数组...那不是家庭作业.我正在准备Java认证.干杯

解决方案

因为你的 uu 是一个 array of array.所以,当你迭代它时,你首先会得到一个array,然后你可以迭代这个数组来获取单个元素.

因此,您的外循环将 int[] 作为类型,因此是该声明.如果您在另一个内部循环中遍历您的 u,您将获得 int 类型:-

for (int[] u: uu) {for (int elem: u) {//你的个人元素}}

This is the snippet of Java code:

int[][] uu = new int[1][1];
uu[0][0] = 5;
for(int[] u: uu){
    System.out.println(u[0]);
}

It prints 5. But why does the declaration part of for loop is declared as int[] u, but not as int[][] u?

At the uu you reference 2D array... That is not a homework. I am preparing for Java certification. Cheers

解决方案

Since your uu is an array of array. So, when you iterate over it, you will first get an array, and then you can iterate over that array to get individual elements.

So, your outer loop has int[] as type, and hence that declaration. If you iterate through your u in one more inner loop, you will get the type int: -

for (int[] u: uu) {
    for (int elem: u) {
        // Your individual element
    }
}

这篇关于对于使用二维数组的每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆