简体   繁体   中英

Building a simple Chess board with recursion in java

I'm trying to build a simple chess board layout in java via recursion but my problem is, that in each recursive call the amount of fields are reduced by one which is wrong. Black fields are represented by a "#" and white fields by space. I've done this with Iteration which was no problem but the recursive approach gives me headaches.

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

}

I know this is not the prettiest code in the world, but it does the trick

I use a second variable calls to calculate the number of recursions needed. With this, I could use the boardlength variable to print each row.

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

}

Output with boardlenth=8 (I change the space for a @)

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

@#@#@#@#

#@#@#@#@

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM