在java中检查数组数组中元素的相邻元素

在java中检查数组数组中元素的相邻元素,java,arrays,Java,Arrays,所以,我有一个char表 [[.,*,.,.,*] [*,.,.,.,.] [.,.,.,*,*]] 我想把每一个。转换为一个数字,表示相邻字段中有多少个*。基本上是一艘简单的扫雷艇。 是否有一种优雅的方法来检查每个元素的每个相邻字段? 因为我想到的是很多嵌套for cycles和if语句,但我确信有更好的方法可以做到这一点 编辑:预期结果应类似于: [[3,*,2,.] [*,*,2,.]] 我能想到的最优雅的方式是: public static void main(String[] a

所以,我有一个char表

[[.,*,.,.,*]
[*,.,.,.,.]
[.,.,.,*,*]]
我想把每一个。转换为一个数字,表示相邻字段中有多少个*。基本上是一艘简单的扫雷艇。 是否有一种优雅的方法来检查每个元素的每个相邻字段? 因为我想到的是很多嵌套for cycles和if语句,但我确信有更好的方法可以做到这一点

编辑:预期结果应类似于:

[[3,*,2,.]
 [*,*,2,.]]

我能想到的最优雅的方式是:

public static void main(String[] args) {

    char[] a = {'.', '.', '*', '.', '*'};
    char[] b = {'.', '*', '*', '.', '*'};
    char[] c = {'.', '.', '*', '.', '*'};
    char[] d = {'.', '*', '*', '.', '*'};
    char[] e = {'*', '.', '*', '.', '*'};
    char[][] ae = {a, b, c, d, e};

    char[][] numberArray = new char[5][5];


    for (int i = 0; i < ae.length; i++) {
        for (int j = 0; j < ae[i].length;  j++) {
            numberArray[i][j] = checkAdjacentField(i, j, ae);
        }
    }
    StringBuilder matrix = new StringBuilder();

    for (char[] aNumberArray : numberArray) {
        StringBuilder bld = new StringBuilder("{");
        for (char character : aNumberArray) {
            bld.append(character).append(",");
        }
        bld.deleteCharAt(bld.length() - 1);
        bld.append("}");
        matrix.append(bld.toString()).append("\n");
    }
    System.out.println(matrix.toString());
}

private static char checkAdjacentField(int i, int j, char[][] ae) {
    int count = 0;
    if (j <= ae[i].length - 2) { // to the right
        count += ae[i][j + 1] == '*' ? 1 : 0;
    }
    if (j <= ae[i].length - 2 && i <= ae.length -2) { // move to top right
        count += ae[i + 1][j + 1] == '*' ? 1 : 0;
    }
    if (j <= ae[i].length - 2 && i > 0) { // move to bottom right
        count += ae[i - 1][j + 1] == '*' ? 1 : 0;
    }
    if (j > 0) { // to the left
        count += ae[i][j - 1] == '*' ? 1 : 0;
    }
    if (j > 0 && i <= ae.length -2) { // to top left
        count += ae[i + 1][j - 1] == '*' ? 1 : 0;
    }
    if (j > 0 && i > 0) { // to bottom left
        count += ae[i - 1][j - 1] == '*' ? 1 : 0;
    }
    if (i <= ae.length -2) { // move to top
        count += ae[i +1][j] == '*' ? 1 : 0;
    }
    if (i > 0) { // move top bottom
        count += ae[i - 1][j] == '*' ? 1 : 0;
    }
    System.out.printf("field %s, %s has %s Adjacent fields with a * \n", i, j , count);
    String stringValue = String.valueOf(count);
    return stringValue.charAt(0);
}
如果你对这个例子有疑问,我想听听


下一次,试着提供一个例子,说明你以前已经准备好尝试过的东西。

展示你已经尝试过的东西。没有真正优雅的方法,您必须检查边界。我希望我的结果看起来像[[3,,.][,*,.]您的解决方案,由于某种原因没有计算对角线*?另外,如果我希望CheckNexture方法将“.”替换为数字,而不是只打印它们,我应该对该方法进行哪些修改?除了使其返回char[][]编辑:啊,sry,我不知道如何设置逗号的格式,我将根据预期结果编辑问题我不知道您希望包含对角检查,这将导致在前面4个检查的基础上增加4个if检查。我不会返回字符[][]但我只是更新了答案的字段号。这不是最干净的代码,但我认为现在就可以了