列印小屋星形圖案的程式
解決有趣的模式問題可以增強對迴圈的理解。它們至關重要,因為它們有助於構建特定程式語言的堅實基礎。各種型別的模式,包括基於數字、基於星號和基於字母的模式。本文將指導您使用 Java 中的巢狀 for 迴圈來解決小屋星形圖案。
列印小屋星形圖案的 Java 程式
由於我們將使用巢狀 for 迴圈來解決問題,因此有必要討論其語法。
語法
for ( initial expression; conditional expression; increment/decrement expression ){
for ( initial expression; conditional expression; increment/decrement expression ) {
// code to be executed
}
}
初始表示式 - 迴圈開始時執行一次。
條件表示式 - 程式碼將在條件表示式為真時執行。
增量/減量表達式 - 用於增加/減少迴圈變數。
圖案
方法
將整個圖案分成兩部分。第一部分是上三角形,第二部分是下矩形。
宣告並初始化一個整數“n”,它指定上部和下部部分的行數。
宣告並初始化空格和星號的初始計數。
現在,對於上三角形部分,定義一個巢狀 for 迴圈。外部 for 迴圈將執行到“n”,第一個內部迴圈將執行到空格計數並列印空格。列印後,將空格計數減 1。
第二個內部 for 迴圈將執行到星號計數並列印星號。列印後,將星號計數增加 2。
再次建立另一個巢狀 for 迴圈。外部 for 迴圈將執行到“n”,第一個內部迴圈將列印左側矩形形狀,第二個內部迴圈將列印空格,最後一個內部迴圈將列印右側矩形形狀。
示例
public class Hut {
public static void main(String[] args) {
// count of upper triangle row and lower rectangle row
int n = 5;
int spc = n-1;
// initial count of space
int str = 1;
// initial count of star
// upper triangular shape
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= spc; j++) {
// for space
System.out.print("\t");
}
spc--;
for(int k = 1; k <= str; k++) {
// for star
System.out.print("*\t");
}
str += 2;
System.out.println();
// to move the cursor to next line
}
// lower rectangular shape
for (int i = 0; i < n; i++) {
// for left rectangular shape
for (int j = 0; j < n/2; j++) {
System.out.print("*\t");
}
// for space
for (int j = 0; j < 5; j++) {
System.out.print("\t");
}
// for right rectangular shape
for (int j = 0; j < n/2; j++) {
System.out.print("*\t");
}
System.out.println();
// to move the cursor to next line
}
}
}
輸出
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
結論
在本文中,我們討論了小屋星形圖案的解決方案。我們藉助巢狀 for 迴圈解決了這個問題。這將幫助您解碼模式問題的邏輯,並使您能夠自己解決其他模式。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP