我正在尝试使用用户输入的宽度为7来打印钻石,该宽度应该如下所示:
*
* *
* *
* *
* *
* *
*
但不幸的是,我的钻石在底部搞砸了,看起来像这样:
*
* *
* *
* *
* *
*
这是我的代码:
public static void main (String[] args)
{
int width = 0;
System.out.println("What is the width?");
Scanner keyboard = new Scanner (System.in);
width = keyboard.nextInt();
//Print top half of the diamond
for (int i = 0; i < width; i += 2) {
if (i == 0) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j < width - i; j += 2) {
System.out.print(' ');
}
System.out.print('*');
for (int j = 0; j < i - 1; j++) {
System.out.print(' ');
}
System.out.print('*');
}
System.out.print('\n');
}
//Print bottom half of the diamond
for (int i = 0; i < 3; i+=2) {
if (i == 2) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j <= i + 2; j += 2) {
System.out.print(' ');
} System.out.print ('*');
for (int j = 0; j < (width / 2) - i; j++) {
System.out.print(' ');
} System.out.print('*');
}
System.out.print('\n');
}
}
我不完全确定如何修复它的底部,这就是我一直想弄清楚的!这些嵌套的for循环很棘手
答案 0 :(得分:0)
尝试将下半部分中的3更改为4循环。似乎缺少一行。那可能会这样做。不能保证我是新来的,只是想帮忙! :)
答案 1 :(得分:0)
对于简单修复,请将底部循环变量i
从3
更改为5
,并在i
之后从2
更改为4
//Print bottom half of the diamond
for (int i = 0; i < 5; i+=2) {
if (i == 4) {
for (int j = 0; j < (width / 2) + 1; j++)
System.out.print(' ');
System.out.print('*');
} else {
for (int j = 0; j <= i + 2; j += 2) {
System.out.print(' ');
} System.out.print ('*');
for (int j = 0; j < (width / 2) - i; j++) {
System.out.print(' ');
} System.out.print('*');
}
System.out.print('\n');
}