如何使用数组绘制X?

时间:2017-07-29 08:44:23

标签: java

有没有人知道如何从给定数字打印X? e.g:

给出5号。 所以,我应该打印

 X000X
 0X0X0
 00X00
 0X0X0
 X000X

这是我的代码,但仍遗漏了一些东西

public static void drawX(int number){
    int[][] draw = new int[number][number];
    for(int i = 0; i< number; i++){
        for(int k = 0; k<=i; k++){
            System.out.print(" ");
        }
        for(int j = number-1; j>i; j--){
            if(j == number-1 || j == i+1)
                System.out.print("X ");
            else
                System.out.print("  ");
        }
        System.out.println();
    }
    for(int i = 0; i< number; i++){
        for(int v = number; v>i; v--){
            System.out.print(" ");
        }
        for(int j = 0; j<i; j++){
            System.out.print("X ");
        }
        System.out.println();
    }
 }

1 个答案:

答案 0 :(得分:1)

请参阅下面的对您的代码的评论,突出显示我发现的一些问题。它可能不会马上解决所有问题,但它会让你朝着正确的方向努力。

public static void drawX(int number){
    // draw is never used.
    int[][] draw = new int[number][number];
    for(int i = 0; i< number; i++){
        for(int k = 0; k<=i; k++){
            // Here we print a " " even for k == i.
            // Are you sure you want k <= i ?
            // If you change it, dont forget to also change
            // stop clause in next loop.
            System.out.print(" ");
        }
        for(int j = number-1; j>i; j--){
            if(j == number-1 || j == i+1)
                // j == number -1 prints X only in the last column
                // Maybe you wanted number - i - 1?
                // j == i+1 means you "skip" the ith element.
                // Why the extra space after X?
                System.out.print("X ");
            else
                // Why two spaces here?
                System.out.print("  ");
        }
        System.out.println();
    }
    for(int i = 0; i< number; i++){
        for(int v = number; v>i; v--){
            System.out.print(" ");
        }
        for(int j = 0; j<i; j++){
            // here you need to do very similar logic to 
            // what you did in previous loop, when printing first
            // 'number' lines.
            System.out.print("X ");
        }
        System.out.println();
    }
 }