在 java 中用递归构建一个简单的国际象棋棋盘

Building a simple Chess board with recursion in java

我正在尝试通过递归在 java 中构建一个简单的棋盘布局,但我的问题是,在每次递归调用中,字段的数量都减少了一个,这是错误的。黑色字段由“#”表示,白色字段由 space 表示。我用 Iteration 完成了这个,这没问题,但是递归方法让我头疼。

import java.util.Scanner;

public class Chess {

public static int chess(int boardlength) {

    if (boardlength == 0) {
        return boardlength;
    } else {
        pattern(boardlength);
        System.out.println("\n");
    }
    return chess(boardlength - 1);
}

    public static int pattern(int runs) {

        if (runs == 0) {
            return runs;
        } else {
            if (runs % 2 != 0) {
                System.out.print("#");
            } else {
                System.out.print(" ");
            }
        }
        return pattern(runs - 1);
    }

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Length of the board: ");
    int boardlength = input.nextInt();
    chess(boardlength);
}

}

我知道这不是世界上最漂亮的代码,但它确实有用

我使用第二个变量 calls 来计算所需的递归次数。有了这个,我可以使用 boardlength 变量来打印每一行。

import java.util.Scanner;

public class Chess {

  public static int chess(int boardlength, int calls) {

    if (calls == boardlength ) {
      return boardlength;
    } else {
      pattern(boardlength, calls % 2 != 0);
      System.out.println("\n");
    }
    return chess(boardlength, calls + 1);
  }

  public static int pattern(int runs, boolean pat) {

    if (runs == 0) {
      return runs;
    } else {
      if (pat) {
        System.out.print("#");
      } else {
        System.out.print("@");
      }
    }
    return pattern(runs - 1, !pat);
  }

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Length of the board: ");
    int boardlength = input.nextInt();
    chess(boardlength, 0);
  }

}

boardlenth=8输出(我把space改成了@)

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@