如果将5
插入到下面的sc.input
中:
*
***
*****
但是,我得到了下面:
*
***
*****
有什么问题吗?
public void test3() {
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
for(int i=0; i<n1; i++){
if(i<=n1/2){
for(int j=0; j<n1; j++) {
if( j<(n1/2)-i || j>(n1/2)+i ) {
for(int m=0; m<(n1/2)-i; m++){
System.out.print(" ");
}
} /*else if( j==2 ) {
System.out.print("*");
}*/ else {
System.out.print("*");
}
}
System.out.println();
}
}
}
2条答案
按热度按时间ppcbkaq51#
我注意到打印的每一行都有一个奇数的 *。用户输入是收集行数,还是收集最后一行的最大 * 数?如果输入收集要打印到屏幕上的行数,那么可以按下面的代码所示进行。
如果输入是收集最后一行中 * 的个数,那么平衡 * 的奇数行/偶数行就有点棘手了
ecbunoof2#
您的循环中存在一些逻辑错误:
(#numbers)
):1.为什么要循环到
n1-1
并检查n1/2呢?这样你就跳过了一半的迭代,这是毫无意义的。只要循环到n1/2
,这样你就可以避免if-conditional
。更妙的是:让我们数一下后院;以后会有用的
1.我们需要一个品牌,你的条件,以了解当一个空间必须打印。
i
),我们需要打印更多的空格。随着i
的减少,我们将有越来越少的空格(直到最后一行,我们将有0个空格)。您只需要建立一个范围:因为范围是从0到
n1-1
,所以j>n1-i-1
中的最后一个-1是必需的1.在
j
上找到打印空间的正确条件后,我们就可以了。因此,我们不再需要forloop
来打印空间请注意,此逻辑也适用于
n1
的偶数值。n1=7
的输出**:n1=8
的输出**: