共計 641 個字符,預計需要花費 2 分鐘才能閱讀完成。
以下是一個打印菱形的 Java 代碼示例:
import java.util.Scanner;
public class DiamondPattern {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);
System.out.print(" 請輸入菱形的行數:");
int rows = scanner.nextInt();
int spaces = rows - 1;
int stars = 1;
// 打印上半部分
for (int i = 1; i <= rows; i++) {for (int j = 1; j <= spaces; j++) {System.out.print(" ");
}
for (int j = 1; j <= stars; j++) {System.out.print("*");
}
System.out.println();
spaces--;
stars += 2;
}
// 打印下半部分
spaces = 1;
stars = rows * 2 - 3;
for (int i = 1; i <= rows - 1; i++) {for (int j = 1; j <= spaces; j++) {System.out.print(" ");
}
for (int j = 1; j <= stars; j++) {System.out.print("*");
}
System.out.println();
spaces++;
stars -= 2;
}
}
}
運行程序后,會提示輸入菱形的行數,輸入后即可打印出對應行數的菱形圖案。
丸趣 TV 網 – 提供最優質的資源集合!
正文完