java - 处理二维整数数组的行
问题描述
在此先感谢您的帮助。我是 Java 新手,在处理 2D 整数数组的行时遇到了困难。我已经搜索了这个论坛和其他资源丰富的地方,但没有任何帮助。
以下是数组元素:
1 2 3 4
4 9 17 26
2 4 6 8
1 3 5 7
9 12 32 33
4 8 10 16
3 7 9 21
10 11 12 13
这是我的错误代码:
for (int row=0; row<list.length; row++) {
for (int col=0; col<list[row].length; col++) {
if (list[row][0] + 1 != list[row][1] &&
list[row][1] + 1 != list[row][2] &&
list[row][2] + 1 != list[row][3]) {
System.out.print(list[row][col] + " ");
}
}
System.out.println()
假设您不知道数组元素的值,我需要一个代码来测试和打印其元素不连续递增 1 的数组行,例如 1 2 3 4 和 10 11 12 13。
解决方案
您可以遍历整个列,比较每个值,并使用布尔值来跟踪它们是否连续递增。像这样的东西:
boolean rowIsConsecutive;
int previousValue;
for (int row = 0; row<list.length; row++)
{
rowIsConsecutive = true;
previousValue = list[row][0]; // This will blow up with a 1D array. Just wrote it like this for readability.
for (int col = 1; col<list[row].length && rowIsConsecutive; col++)
{
if (list[row][col] == previousValue + 1)
{
previousValue = list[row][col];
}
else
{
rowIsConsecutive = false;
}
}
if (rowIsConsecutive)
{
System.out.println(Arrays.toString(list[row]));
}
}
免责声明:我没有对此进行测试,但是这些方面的东西应该可以工作。我把它留给你想出一种更高效的方法来做到这一点:)
推荐阅读
- mongodb - 如何在 mongodb 中设置自我加入
- image - Github页面jekyll图像未加载
- html - 如何检查每个表单控件是否在响应式表单中更改了它们的值?
- python - 我可以使用 Dataframe.between_time 函数同时选择两个时间段吗?
- docker - docker run CLI - \ 后的空白产生`iinvalid reference format`
- c# - C# 回调函数不是从 C++ 代码调用的
- android - 类型“_Type”不是“颜色”类型的子类型
- android - 如何保持多边形的状态?
- javascript - node.js 获取返回 index.html 而不是 json 的 post 请求
- angular - NgRx:获取“您在预期流的位置提供了‘未定义’。” 调用完整动作时生效