0

The work I am currently doing requires me to 'draw' a square by printing '*' as the outline and '.' to fill it in. My code seems to work but it still isn't accepting it. I am a beginner, thanks.

class Main {

    public static void main(String args[]) {

        int square = 5;
        int line = 1;
        int stars = 1;
        int startLine = square / square;

        while (line <= startLine) {

            while (stars <= square) { // first line prints out dots for the value of square, in this case 5
                System.out.print("*");
                stars = stars + 1;
            }

            System.out.println();
            line = line + 1;                //prints new line and adds 1 to line. Meaning it will move to the next section as it is now greater than startLine
        }

        stars = 1;              //resets stars

        while (line <= square - 1) {// line will keep looping until its value is greater than square - 1

            while (stars <= startLine) {
                System.out.print("*");         // First character to print is *
                stars = stars + 1;
            }

            while (stars <= square - 1) {
                System.out.print(".");          //prints 3 dots
                stars = stars + 1;
            }

            while (stars <= square) {
                System.out.print("*");         // stars is equal to square so 1 star is printed 
                stars = stars + 1;
            }

            stars = 1;
            System.out.println();
            line = line + 1;              // adds a value and loops around again
        }

        stars = 1;
        while (line <= square) {

            while (stars <= square) {
                System.out.print("*");
                stars = stars + 1;
            }

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

It seems to make up the square and if I change the value of 'square' the size changes too. I can't see the problem.

4

1 回答 1

0

有更好的方法可以做到这一点,然后为每一行设置一个循环。您可以考虑的一件事是您知道它是一个正方形,因此在您的情况下它总是像 5x5 或 6x6、7x7 等...

假设 x 表示正方形的宽度,y 表示正方形的高度。当您的索引为 , 和其他任何内容时,您只*x5需要星号5x*“ ”1x**x1.

所以这里有一些伪代码

get width or height from user then set either the height or the width to the same thing that way its a square

for loop 1 to 5 //x - width
    for loop 1 to 5 //y - height
        if (check for *x5, 5x*, 1x* and *x1) //you can make a couple IF's if you want
            print a star
        else 
            print a dot
        end if
     print new line ("\n")
    next
next

我希望这有帮助。

于 2012-07-19T13:20:29.737 回答