在java中使用递归构建一个简单的棋盘

edqdpe6u  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(399)

我试图通过递归在java中构建一个简单的棋盘布局,但我的问题是,在每个递归调用中,字段的数量减少了一个错误的字段。黑场用“#”表示,白场用空格表示。我用迭代的方法做过,这没问题,但是递归方法让我头疼。

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);
}

}

rhfm7lfc

rhfm7lfc1#

我知道这不是世界上最漂亮的代码,但它确实起到了作用
我使用第二个变量 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 (我将空格改为@)
@#@#@#@#

@#@#@#@

@#@#@#@#

@#@#@#@

@#@#@#@#

@#@#@#@

@#@#@#@#

@#@#@#@

相关问题