java - 如何用二维数组上的 foreach 循环来表达我的 for 循环?
问题描述
public static boolean doit(int[][] a, int b){
for(int i=0; i<a.length; i++){
for (int j = 0; j < a[i].length; j++)
{
if(a[i][j] ==b) {
return true;
}
}
}
return false;
}
所以基本上我想使用ForEach
循环来检查数组是否包含int b
,但我不知道如何使用它。
public static boolean doitTwo(int[][] a, int b){
for(c :a){
for ( d:a){
if(a[c][d] ==b) {
return true;
}
}
}
}
解决方案
快到了,但是a
当内部循环应该使用c
. 此外,当您迭代值而不是像这样的索引时,您不需要对数组进行索引(就像您对 所做的那样a[c][d]
),因为您已经拥有了这些值。
public static boolean doitTwo(int[][] a, int b){
for(int[] c : a){
for (int d : c){
if(d ==b) {
return true;
}
}
}
我还在你的 for 循环中添加了类型,这不是绝对必要的,因为它们可以被推断出来,但我更喜欢在 Java 中显式。
第一个 for 循环c : a
采用 a 并迭代其值。因为它是一个二维数组,所以它的每个元素都是一个一维数组!然后迭代该一维数组,一维数组的每个值都是 int。
示例伪代码:
# Original 2D array which is an array, containing arrays of ints. i.e. int[][]
x = [[1, 2, 3], [4, 5, 6];
for (a : x) {
# at this point on the first iteration, a = [1,2,3]. i.e. int[]
for (b : a) {
# at this point on the first iteration, b = 1. i.e. int
}
}
推荐阅读
- google-apps-script - 如何计算字母差异?
- azure - Azure Cloud Shell 与 Bastion 有什么区别?
- c - C 代码错误(从 Raspberry Pi 零 W 读取 GPIO 输入),在 Jessie 上编译,但在 Buster Lite 上不编译
- c - 为什么返回 42 而不是 682?
- php - PHP cURL 返回加密的 html 页面
- python - 如何使用opencv在视频上绘制尾随线
- php - 如何将 Log in 控制器放入 laravel 项目?
- c# - 无法序列化流数据asp .net core
- java - Jsoup 抓取图片 url 结果 data:image/gif;base64,
- ios - Swift 中的剪辑形状