java里面draw使用星号,如何用星号绘制钻石

博客围绕Java中使用星号绘制菱形展开。作者起初尝试绘制菱形的上半部分(正三角形)和下半部分(倒三角形),但未能成功组合成完整菱形。最后给出解决方案,通过定义drawDiamond、drawTop和drawBot方法实现菱形绘制。

For my assignment I am supposed to make a Draw a diamond with asterisks using methods.

I figured out how to make the first part (centered triangle)

I cannot for the love of God figure it out. I have spent over 4 hours trying different things and I figured how to make an upside down triangle, but the diamond is not working out.

This is what I have for the first part. Can someone tell me how to flip it so that it will form a diamond when used with an upside down version?

{

int rows = userInputHeight;

int starCount = 1;

int spaceCount = rows - 1;

for( int rowCount = 1; rowCount <= rows; rowCount++ )

{

for( int numb = 1; numb <= spaceCount; numb++ )

{

System.out.print(" ");

}

for( int count = 1; count <=starCount; count++ )

{

System.out.print("*");

}

System.out.println();

starCount += 2;

spaceCount--;

}

}

This is what it displays (UserInputHeight = 10):

*

***

*****

*******

*********

***********

This is what I want (UserInputHeight = 19):

*

***

*****

*******

*********

***********

***********

*********

*******

*****

***

*

This is what I have so far for the second part:

{

int rows = userInputHeight;

int starCount = rows*2;

int spaceCount =userInputPadding;

if (userInputHeight % 2 == 0)

{

userInputHeight+=1;

}

for (int rowCount = rows; rowCount >= 1; rowCount --)

{

for (int i = 0; i <= (rows - rowCount)+ spaceCount; i++)

{

System.out.print(' ');

}

for (int i = 1; i < starCount; i++)

{

System.out.print('*');

}

System.out.println();

starCount -=2;

}

}

Please help.

解决方案

Try this:

public static void drawDiamond(int height) {

if (height % 2 == 0) throw new AssertionError("Height should be an odd number!");

height = (height + 1) / 2;

drawTop(height);

drawBot(height - 1);

}

public static void drawTop(int height) {

int rows = height;

int starCount = 1;

int spaceCount = rows - 1;

for (int rowCount = 1; rowCount <= rows; rowCount++) {

for (int i = 0; i < spaceCount; i++) {

System.out.print(" ");

}

for (int i = 0; i < starCount; i++) {

System.out.print("*");

}

starCount += 2;

spaceCount--;

System.out.println();

}

}

public static void drawBot(int height) {

int rows = height;

int starCount = 2 * (rows - 1) + 1;

int spaceCount = 1;

for (int rowCount = 1; rowCount <= rows; rowCount++) {

for (int i = 0; i < spaceCount; i++) {

System.out.print(" ");

}

for (int i = 0; i < starCount; i++) {

System.out.print("*");

}

starCount -= 2;

spaceCount++;

System.out.println();

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值