java-打印x^x^x正方形

8ljdwjyq  于 2021-07-06  发布在  Java
关注(0)|答案(4)|浏览(328)

我有一个任务要做,我的任务是打印x个正方形的x^x。例如,输入“3”的正确输出如下图所示
示例如下:

我的代码:

Scanner s = new Scanner (System.in);
int base, k=0;
System.out.println("Enter a number do draw some squares");
base = s.nextInt();
int bb = base*base;

for (int t=0; t<=bb; t++) {
    if (t<bb) {
        for (int i=0; i<base; i++) {
            for (k=0; k<=base; k++) {
                if (k<base) 
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
        }
    }
    System.out.println();
}

尝试使用“2”作为基时,输出为:


****
****
****
****

我的输出:

如何计算每两行之间的空格?
真诚地,

ilmyapht

ilmyapht1#

你可以利用模运算符( % )选择第n行。

oiopk7p5

oiopk7p52#

当循环计数器可被基数整除时,即 the_loop_counter % base = 0 .

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a number do draw some squares: ");
        int base = s.nextInt();
        int bb = base * base;

        for (int i = 1; i <= bb; i++) {
            for (int j = 1; j <= bb; j++) {
                System.out.print(j % base == 0 ? "* " : "*");
            }
            System.out.println(i % base == 0 ? System.lineSeparator() : "");
        }
    }
}

示例运行:

Enter a number do draw some squares: 3

*********
*********
*********

*********
*********
*********

*********
*********
*********
szqfcxe2

szqfcxe23#

Scanner s = new Scanner (System.in);
int base, k=0;
System.out.println("Enter a number do draw some squares");
base = s.nextInt();
int bb = base*base;

for (int t=0; t<=bb; t++) {
    if (t<bb) {
        if(t%base == 0) {
           System.out.println();
        }
        for (int i=0; i<base; i++) {
            for (k=0; k<=base; k++) {
                if (k<base) 
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
        }
    }
    System.out.println();
}

https://ideone.com/md8kol

qyzbxkaa

qyzbxkaa4#

我会使用4个嵌套循环:

static void printSquares(int n) {
    for (int boxRow = 0; boxRow < n; boxRow++) {
        for (int starRow = 0; starRow < n; starRow++) {
            for (int boxCol = 0; boxCol < n; boxCol++) {
                for (int starCol = 0; starCol < n; starCol++) {
                    System.out.print('*');
                }
                System.out.print(' ');
            }
            System.out.println();
        }
        System.out.println();
    }
}

的输出 printSquares(2) ```





的输出 `printSquares(3)` ```

*********
*********
*********

*********
*********
*********

*********
*********
*********

相关问题