我目前正在做的工作要求我通过打印'*'作为轮廓和''来'画'正方形。填写它。我的代码似乎工作但它仍然不接受它。我是初学者,谢谢。
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;
}
}
}
似乎构成了正方形,如果我改变'square'的值,那么尺寸也会改变。我看不出问题。
答案 0 :(得分: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
我希望这会有所帮助。