首页 > 解决方案 > 如何通过Java中的给定位置打印矩阵的垂直和水平线?

问题描述

例如我们有一个矩阵:

a b j d e f g k
l m a o p y e s
o k v h e l l o
t h a n k s a m

我有一个给定位置:字符 v 的 row[2] col[2]。我想根据该位置或我得到的任何其他位置打印水平线和垂直线。

我在那个特定位置的水平线应该是:

o k q h e l l o

还有我的垂直线:

j a v a

标签: javaloopsmultidimensional-arrayposition

解决方案


这里“最棘手”的事情实际上只是考虑了您想要的格式。

当我们遍历数组时,对于某些列,我们只需要确保ij等于我们的行或列。例如 - 因为i对应于我们二维数组中元素的第一个元素:

{“a”、“b”、“j”、“d”、“e”、“f”、“g”、“k”}

那么我们知道i所有这些元素都必须等于 0。因此我们可以得出结论,要打印一些行,我们只需要确保ieqaul 与我们想​​要的行号。我们可以应用类似的逻辑来抓取我们的列。

public class Test {
    private String[][] data = {{"a", "b", "j", "d", "e", "f", "g", "k"}, // i == 0
                               {"l", "m", "a", "o", "p", "y", "e", "s"}, // i == 1
                               {"o", "k", "v", "h", "e", "l", "l", "o"}, // i == 2
                               {"t", "h", "a", "n", "k", "s", "a", "m"}}; // i == 3
                         // j == 0    1    2    3    4    5    6    7

    public static void main(String[] args) {
        new Test();
    }

    /**
     * Test each of our methods.
     */
    public Test() {
        // GET THE 3RD (POSITION 2) ROW
        System.out.println(getRow(data, 2));

        // GET THE 6TH (POSITION 5) COLUMN
        System.out.println(getCol(data, 5));
    }

    /**
     * Get some row of some 2D array. This method does not check that
     * the row is within the bounds of the 2D array.
     * 
     * @param data
     * @param row
     * @return
     */
    private String getRow(String[][] data, int row) {
        String s = "";

        int numRows = data.length;
        int numCols = data[0].length;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < numCols; j++) {
                if (i == row) {
                    s += data[i][j];
                    if (i < (numRows - 1)) s += " ";
                }
            }
        }

        return s;
    }

    /**
     * Get some column of some 2D array. This method does not check that
     * the column is within the bounds of the 2D array.
     * 
     * @param data
     * @param col
     * @return
     */
    private String getCol(String[][] data, int col) {
        String s = "";

        int numRows = data.length;
        int numCols = data[0].length;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < numCols; j++) {
                if (j == col) {
                    s += data[i][j];
                    if (j < (numCols - 1)) s += " ";
                }
            }
        }

        return s;
    }
}

推荐阅读