java - 嵌套 For 循环说明
问题描述
用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();
}
}
解决方案
您缺少 else 条件,if (((input + 1) / 2) != ir)
如下所示:
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("*");
}
// Added else
} else {
for (int ic = 1; ic <= (input - ir); ic++) {
System.out.print("*");
}
}
if ((input / 2) < ir) {
stars--;
spaces += 2;
} else {
stars++;
spaces -= 2;
}
System.out.println();
}
} else {
return;
}
scnr.close();
}
}
然而,您的代码有点难以阅读和理解。您可能需要对其进行一些重构。
推荐阅读
- php - 如何在使用 cookie 进行登录身份验证时重新生成登录令牌
- javascript - TSLint ,在 import 语句中强制括号之间的间距
- javascript - 看跌价值在一个变量中
- angular - 角类不工作
- r - 创建一个包含许多矩阵的块对角矩阵
- java - 尝试从 Eclipse 氧气运行 Tomcat [Liferay] 时出错
- javascript - 如果值包含,如何获取数组中键的索引?
- reactjs - Apollo GraphQL:更改默认标题 INSIDE React 子组件
- lambda - 如果我们可以简单地传递一个正则 Lambda 表达式来代替 Vaadin 8 中定义的 `SerializableFunction` 接口,它的目的是什么?
- ruby-on-rails - Rails:model.validate - 参数数量错误