java - 如何在二维数组中查找和打印搜索元素的位置(行和列)?
问题描述
我是一个完整的编程新手,目前正在学习数组。我想7
在控制台中打印出数字,这很有效。现在,我还想打印出数字 7 所在的特定行和行:“7 位于第 2 行和第 1 行。”。如何找到数字的行和列7
?
public static void main(String[] args) {
int[][] array2 = {
{3,4,5},
{1,3,6},
{5,7,9}
};
System.out.println(array2[2][1]);
}
}
解决方案
public static void main(String[] args) {
int elementSearched = 7;
int[][] array2 = {
{3, 4, 5},
{1, 3, 6},
{5, 7, 9}
};
for (int i = 0; i < array2.length; i++)
for (int j = 0; j < array2[0].length; j++) {
if (array2[i][j] == elementSearched) {
System.out.println(elementSearched + " is located in line " + i + " and row " + j + ".");
}
}
}
array2[0] 用于获取行的 sizew(本例中为 3)
这里要做的主要事情就是通过 2 个 for 循环对数组进行蛮力搜索。
推荐阅读
- php - 如何显示该类别中的产品数量?在 laravel 中使用 Eloquent ORM
- reactjs - 如何在 Reactjs 中提交表单?(表格提交)
- omnet++ - 如何确定是否存在网络拥塞?或如何在 V2V 和 V2I 网络中造成拥塞?
- google-speech-to-text-api - Google Speech to Text API 填充词
- java - 将列表输出到文件
- automation - 仅当活动窗口为给定大小时,如何禁用热键?
- r - 在直方图ggplot2中添加列和每组的总值
- c# - PHP 可以包含“文件名”但 c#?
- uwp - UWP。如何打开多个视频
- java - 反转计数算法实现的问题