使用java绘制ASCII艺术

时间:2011-10-29 17:03:13

标签: java

我有一个问题是绘制一个方形ASCII,其大小限制为20个字符('square'的大小),这是我的代码,我已经过测试并且它可以工作但是当我把这个数字放在20以上它的显示一个错误,请帮助,谢谢。

class Main {
    public static void printSquare(int size) {
        int line = 1;

        while (line <= size) { // For each line of square
            int width = size; // width of square segment
            int i = 1; // display square segment

            while (i <= width && size <= 20) {
                System.out.print("*");
                i = i + 1;
            }

            System.out.println(); // Newline
            line = line + 1;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

问题是,如果大小超过20,你永远不会打印*。将它限制为20的更好方法是限制循环前的大小。

public static void printSquare(int size) {
    if(size > 20) {
       size = 20;
    }
    int line = 1;

然后编辑

while (i <= width && size <= 20) {

while (i <= width) {