我应该根据用户输入的数字创建此模式。用户输入的数字对应于行数和每行中的星号。
*
**
***
****
*****
我被告知只能使用嵌套 for 循环,不能使用 printf()。这只是我正在处理的代码的一部分。
for (int row = 1; row <= size; row++) {
for (int column = 1; column <row; column++) {
System.out.print(" ");
}
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
我似乎无法做出如上所示的输出。相反,我得到了这个:
*
**
***
****
*****
有人可以给我一个提示,告诉我我应该做什么吗?我花了2个小时还是没搞明白。
最佳答案
对于每一行,您应该输出最多 size
个字符;因此,如果 size = 5,在第三行,如果输出三颗星,则需要 size-row
空格 => 5 - 3 = 2。
在代码中:
for (int row = 1; row <= size; row++) {
for (int column = 1; column <= size-row; column++) {
System.out.print(" ");
}
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
关于java - 使用 for 循环的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19461672/