我试图练习如何制作简单的形状,并且无法制作这种特定形状:
X X
X X
X
X X
X X
我想要求用户输入尺寸,然后根据尺寸,它将使用这些尺寸制作形状(如果用户输入5,则上述形状将被打印)。我能够使用这段代码制作一个正方形:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int size = 0;
System.out.print("Enter the size of your shape: ");
size = scan.nextInt();
这将获得用户想要的大小。然后,为了绘制矩形形状,我使用了这个:
static void squareShape(int size){
for(int i = 0;i < size;i++){
for(int j = 0;j < size; j++){
System.out.print("X");
}
System.out.println();
}
}
如果有人可以帮我画X,我将不胜感激:)
答案 0 :(得分:1)
用点替换空格使其更明显:
X.....X
.X...X
..X.X
...X
..X.X
.X...X
X.....X
你需要做的是基本弄清楚,对于每一行,在第一个和第二个X之前要打印多少个空格(尽管中心线上没有第二个X
)。为了简化现在的事情,让我们假设高度始终是奇数。
您可以看到第一个空格数遵循模式{0, 1, 2, 3, 2, 1, 0}
,3
是高度7
的一半,向下舍入。这有助于一个简单的循环计数到中点附近,做中点本身,然后再次倒计时:
for firstSpaces = 0 to height/2 - 1 inclusive
output firstSpaces spaces, an X and a newline
output height/2 spaces, an X and a newline
for firstSpaces = height/2 - 1 to 0 inclusive
output firstSpaces spaces, an X and a newline
第二个空格计数类似于{5, 3, 1, 0, 1, 3, 5}
,其中起始点为height - 2
,并且在第一个循环中每次减少2,每次通过第二个循环增加2。这基本上修改了伪代码如下:
secondSpaces = height - 2
for firstSpaces = 0 to height/2 - 1 inclusive
output firstSpaces spaces and an X
output secondSpaces spaces, an X and a newline
subtract 2 from secondSpaces
output height/2 spaces, an X and a newline
for firstSpaces = height/2 - 1 to 0 inclusive
add 2 to secondSpaces
output firstSpaces spaces and an X
output secondSpaces spaces, an X and a newline
在Python 3(最终的伪代码语言)中汇总了一个概念验证:
def x(sz):
secondSpaces = sz - 2
for firstSpaces in range(sz//2):
print(' ' * firstSpaces,end='X')
print(' ' * secondSpaces,end='X\n')
secondSpaces -= 2
print(' ' * (sz//2),end='X\n')
for firstSpaces in range(sz//2 - 1, -1, -1):
secondSpaces += 2
print(' ' * firstSpaces,end='X')
print(' ' * secondSpaces,end='X\n')
print()
x(3)
x(5)
x(7)
x(15)
表明逻辑是合理的:
X X
X
X X
X X
X X
X
X X
X X
X X
X X
X X
X
X X
X X
X X
X X
X X
X X
X X
X X
X X
X X
X
X X
X X
X X
X X
X X
X X
X X
现在您只需要用您选择的语言编写类似的代码,并且(可能)也可以根据需要提供非奇怪的高度。