0

I'm a student, working on a chutes and ladders game. I had to make the board with 100 space,put 10 random chutes and ladders on the board, and i also have to print the board 10*10. so far everything work until the print the board part. when i use the print method, my board print everything need to print but don't line up nicely. any tips on how I can line up all the printout?

import java.util.Random;
public class ChutesAndLadders {
    String[] board;
    Random ran = new Random();


public void setBoard(String[] b) {
    board = b;
    for(int i=0;i<board.length;i++){
        board[i]="  ";
    }
}

public void makeChutes(int x){
    for(int i=0;i<x;i++){
    int temp = ran.nextInt(board.length);
    if (board[temp].equals("    "))
        board[temp]="C"+x;
    else 
        i--;
    }
}

public void makeLadders(int y){
    for(int i=0;i<y;i++){
    int temp = ran.nextInt(board.length);
    if (board[temp].equals("    "))
        board[temp]="L"+y;
    else 
        i--;
    }
}
    public void printBoard(){
    int counter = 0;
    for(int i=0;i<board.length;i++){
        counter++;
        System.out.print("|"+board[i]);
        if(counter==10){
            System.out.print("|"+"\n");
            counter=0;
        }
    }
}
public static void main(String[] args) {
     ChutesAndLadders cl = new ChutesAndLadders();
     cl.setBoard(new String[100]);
     cl.makeChutes(10);
     cl.makeLadders(10);
     cl.printBoard();
}
}
Min
  • 50
  • 3

1 Answers1

1

There are more problems with the above code than the alignment (for example, it will loop forever without terminating, and the numbers on the chutes and ladders are wrong). But regarding the alignment, the problem is that the strings you're replacing the spaces with are not the same length as the spaces themselves. Use String.format() to pad them to four characters.

The usage will look like this:

board[temp] = String.format("%4s", s)

where s is the chute or ladder.

danben
  • 80,905
  • 18
  • 123
  • 145
  • for some reason my code do stop looping maybe i didn't copy my code right. anyways the String.format really helped i just had to change board[i]=" "; under setBoard to board[i]=String.format("%3s", ""); everything lined up nicely. thx again danben – Min Jan 31 '13 at 04:56