【发布时间】:2021-11-25 07:53:08
【问题描述】:
用java编写的代码
我正在尝试在同一行打印用户输入的“*”数量。
这是我所拥有的:
if (((input / 2) + 1) == ir) {
for (int ij = 1 ; ij <= input; ij++) {
System.out.print("*");
}
}
if 语句正在测试我们是否处于我要制作的形状(领结)的中点。
我觉得我的逻辑和代码是正确的,但输入为 5,
这一行看起来像这样:***
代替:*****
有人可以向我解释为什么会这样吗?
这里是完整的代码:
import java.util.Scanner;
public class BowTie {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
int input = scnr.nextInt();
int stars = 1;
int spaces = input - 2;
if ((input % 2 == 1) && (input >= 1)) {
for (int ir = 1; ir <= input; ir++) {
for (int ic = 1; ic <= stars; ic++) {
System.out.print("*");
}
for (int ic = 1; ic <= spaces; ic++) {
if (((input / 2) + 1) == ir) {
for (int ij = 1; ij <= input; ij++) {
System.out.print("*");
}
} else {
System.out.print(" ");
}
}
if (((input + 1) / 2) != ir) {
for (int ic = 1; ic <= stars; ic++) {
System.out.print("*");
}
}
if ((input / 2) < ir) {
stars--;
spaces += 2;
} else {
stars++;
spaces -= 2;
}
System.out.println();
}
} else {
return;
}
scnr.close();
}
}
【问题讨论】:
-
向我们展示整段代码;不是嵌套循环的 sn-p。一个Minimal Reproducible Example。
-
@ElliottFrisch 现在完整的代码就在那里。
-
太棒了。现在告诉我们您期望
8的输出是什么。因为这对我来说不合适。但我不确定。 -
@ElliottFrisch 代码不会为偶数或小于 1 的任何数字产生输出。我现在看到我不小心没有在此处复制该条件。
标签: java for-loop nested-loops