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

被折叠的 条评论
为什么被折叠?



