我是学习Java的新手,我正在尝试使用星号打印未填充的钻石。钻石的高度必须基于用户输入。我的代码目前根据用户输入打印出一个填充的钻石,但我无法弄清楚如何打印未填充的钻石。每当我改变其中一个循环时,它就会混淆其他东西。感谢所有帮助!
public static void diamond(){
int i = 0;
int j = 0;
int k = 0;
int height = 0;
Scanner in = new Scanner(System.in);
System.out.println("How tall do you want the diamond to be: ");
height = in.nextInt();
for (k = 1; k <= (height + 1) / 2; k++) {
for (i = 0; i < height - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("* ");
}
System.out.println("");
}
for (k = ((height + 1) / 2); k < height; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < height - k; j++) {
System.out.print(" *");
}
System.out.println("");
}
}
答案 0 :(得分:4)
这是修改用于打印未填充钻石的方法。 if条件已添加到内部循环中。
public static void diamond() {
int i = 0;
int j = 0;
int k = 0;
int height = 0;
Scanner in = new Scanner(System.in);
System.out.println("How tall do you want the diamond to be: ");
height = in.nextInt();
for (k = 1; k <= (height + 1) / 2; k++) {
for (i = 0; i < height - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
if (j == 0 || j == (k - 1)) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println("");
}
for (k = ((height + 1) / 2); k < height; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < height - k; j++) {
if (j == 0 || j == (height - k - 1)) {
System.out.print(" *");
} else {
System.out.print(" ");
}
}
System.out.println("");
}
}