如何在for循环java中创建S或K字母

时间:2018-03-16 11:58:01

标签: java for-loop

如何在java中创建S字母或K?我试过这个,但它让ZL

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int n = input.nextInt();
    for (int row = 0; row < n; row++) {
        for (int column = 0; column < n; column++) {
            if (row == 0 || row == n - 1 || column == n - 1 - row) {
                System.out.print("*");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

1 个答案:

答案 0 :(得分:1)

如果您的目标是显示类似的内容(由user6690200建议):

> //K with n=7
> *    *
> *   *
> *  *
> * *
> *  *
> *   *
> *    *

简单的情况只是K因为它是对称的,我不认为你可以使用S的循环。

以下是显示上述K的代码:(仅适用于n不均匀)

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int n = input.nextInt();
    // Higher half of the K
    for (int row = 0; row < (n-1)/2; row++) {
        for (int column = 0; column < n-1; column++) {
            if (column == 0 || column == n-2-row ) {
                System.out.print("*");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
    //Middle line
    System.out.println("* *");
    // Lower half of the K
    for (int row = (n-1)/2-1; row >= 0; row--) {
        for (int column = 0; column < n-1; column++) {
            if (column == 0 || column == n-2-row ) {
                System.out.print("*");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}