Java int[][] 数组 - 迭代和查找值

Java int[][] array - iterating and finding value(Java int[][] 数组 - 迭代和查找值)

本文介绍了Java int[][] 数组 - 迭代和查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 'int[][]' 形式的数组,它表示一个小网格的坐标.每个坐标都被分配了自己的值.例如 array[0][4] = 28......

I have an array in the form of 'int[][]' that represents the co-ordinates of a small grid. Each co-ordinate has been assigned its own value. eg array[0][4] = 28......

我有两个问题.首先,我如何遍历所有存储的值.其次,我希望能够输入一个值并返回其在网格中的特定坐标.解决这个问题的最佳方法是什么?

I have two questions. Firstly, how do I iterate through all the stored values. Secondly, I want to be able to input a value and have its specific co-ordinates in the grid returned. What would be the best way to approach this?

感谢您的帮助!

推荐答案

您可以使用 for 循环或增强的 for 循环进行迭代:

You can iterate with either for loops or enhanced for loops:

for (int row=0; row < grid.length; row++)
{
    for (int col=0; col < grid[row].length; col++)
    {
        int value = grid[row][col];
        // Do stuff
    }
}

// Note the different use of "row" as a variable name! This
// is the *whole* row, not the row *number*.
for (int[] row : grid)
{
    for (int value : row)
    {
         // Do stuff
    }
}

第一个版本将是查找坐标"问题的最简单解决方案 - 只需检查内部循环中的值是否正确.

The first version would be the easiest solution to the "find the co-ordinates" question - just check whether the value in the inner loop is correct.

这篇关于Java int[][] 数组 - 迭代和查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java int[][] 数组 - 迭代和查找值

基础教程推荐