共計 682 個字符,預計需要花費 2 分鐘才能閱讀完成。
以下是一個用 for 循環打印空心菱形的 Java 程序:
import java.util.Scanner;
public class HollowDiamond {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);
System.out.print(" 請輸入菱形的行數:");
int rows = scanner.nextInt();
// 打印上半部分
for (int i = 1; i <= rows; i++) {for (int j = 1; j <= rows - i; j++) {System.out.print(" ");
}
System.out.print("*");
if (i > 1) {for (int j = 1; j <= 2 * i - 3; j++) {System.out.print(" ");
}
System.out.print("*");
}
System.out.println();}
// 打印下半部分
for (int i = rows - 1; i >= 1; i--) {for (int j = 1; j <= rows - i; j++) {System.out.print(" ");
}
System.out.print("*");
if (i > 1) {for (int j = 1; j <= 2 * i - 3; j++) {System.out.print(" ");
}
System.out.print("*");
}
System.out.println();}
}
}
這個程序通過兩個嵌套的 for 循環來打印菱形的每一行。外層循環控制行數,內層循環控制每一行中的空格和星號的個數。
丸趣 TV 網 – 提供最優質的資源集合!
正文完