反向Java For循环
我有这个代码,我正试图打印出以下形状反向Java For循环,java,Java,我有这个代码,我正试图打印出以下形状 **** * * ** * 当前代码: System.out.print("\nEnter number of rows: "); rows = kybd.nextInt(); for (int i = 0; i < rows; i++) { System.out.print("*"); } for (int i = 0; i < rows; i++) { for (int j = 1; j <
****
* *
**
*
当前代码:
System.out.print("\nEnter number of rows: ");
rows = kybd.nextInt();
for (int i = 0; i < rows; i++) {
System.out.print("*");
}
for (int i = 0; i < rows; i++) {
for (int j = 1; j <= i; j++) {
if (j == 1 || j == rows - 1 || j == i) {
System.out.print("*");
} else {
System.out.print("0");
}
}
System.out.println();
}
知道如何反转第二个for循环,使其以另一种方式打印吗?注意,您是在一个单独的循环中打印出第一行星号,而不是在主循环内。如果你想沿着这条路走,你需要把第一个周期放在第二个周期后面
for (int i = 0; i < rows; i++) {
for (int j = 1; j <= i; j++) {
if ((j == 1) || (j == (rows - 1)) || (j == i)) {
System.out.print("*");
} else {
System.out.print("0");
}
}
System.out.println();
}
for (int i = 0; i < rows; i++) {
System.out.print("*");
}
for(int i=0;i 对于(int j=1;j请注意,您是在一个单独的循环中打印出星号的第一行,而不是在主循环中。如果您想沿着这条路走,您需要将第一个循环放在第二个循环之后
for (int i = 0; i < rows; i++) {
for (int j = 1; j <= i; j++) {
if ((j == 1) || (j == (rows - 1)) || (j == i)) {
System.out.print("*");
} else {
System.out.print("0");
}
}
System.out.println();
}
for (int i = 0; i < rows; i++) {
System.out.print("*");
}
for(int i=0;i 对于(int j=1;j我觉得您应该更改I
循环
for (int i = rows - 1; i > 0 ; i--)
我觉得你应该改变你的I
循环
for (int i = rows - 1; i > 0 ; i--)
试试这个:
Scanner kybd = new Scanner(System.in);
System.out.print("\nEnter number of rows: ");
int rows = kybd.nextInt();
if (rows > 1) {
for (int i = 0; i < rows; i++)
System.out.print("*");
System.out.println();
for (int i = rows - 1; i > 1; i--) {
System.out.print("*");
for (int j = 2; j < i; j++)
System.out.print(" ");
System.out.println("*");
}
}
System.out.println("*");
试试这个:
Scanner kybd = new Scanner(System.in);
System.out.print("\nEnter number of rows: ");
int rows = kybd.nextInt();
if (rows > 1) {
for (int i = 0; i < rows; i++)
System.out.print("*");
System.out.println();
for (int i = rows - 1; i > 1; i--) {
System.out.print("*");
for (int j = 2; j < i; j++)
System.out.print(" ");
System.out.println("*");
}
}
System.out.println("*");
出于某种原因…您想让我们找到原因,因为您不知道如何调试?System.out.print(“0”)
是如何实现的?您想For(int i=rows-1;i>0;i--)
。在进一步讨论之前,您想阅读有关循环的所有内容。出于某种原因……您想让我们找到原因,因为您不知道如何调试?系统.out.print(“0”)
是如何实现的?您想for(int i=rows-1;i>0;i--)
。在进一步讨论之前,您希望阅读有关
循环的所有。(尽管我认为“正确的解决方案”是正确的。一个任务可能是合并循环逻辑,这确实解释了该行为。)这不符合OP的要求。-1。@DavidWallace这个答案正确地解释了问题-仅仅修复第二个循环(不包括终端魔法)是无法解决的-并提供了一个解决方案。虽然我认为这不是“适合类”的解决方案,但现在又回到OP上了。OP需要修复他的问题,但是嘿,你的电话:)(虽然我认为“正确的解决方案”是正确的。分配可能是合并循环逻辑,但这确实解释了行为。)这不符合OP的要求。-1。@DavidWallace这个答案正确地解释了问题-仅修复第二个循环(不包括终端魔术)是无法解决的-并提出了一个解决方案。虽然我认为这不是一个“针对类的正确”解决方案,但现在又回到了OP上。OP需要解决他的问题,但嘿,你的电话:)