java中如何打印規(guī)定圖案
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
*
***
*****
*******
*****
***
*
提示: 1)本題上面的圖案和下面的圖案是一樣的。所以在打印上面圖案的時(shí)候,把圖案一行一行的都記錄在數(shù)組b[i]當(dāng)中。
打印下面的圖案時(shí),直接就用上面那個(gè)數(shù)組反向 打印出來(lái)就可以了。馬克-to-win
2)找一下規(guī)律,第一行左邊有三個(gè)空格,中間有一個(gè)星號(hào),右邊有三個(gè)空格,第二行左邊有兩個(gè)空格,中間有三個(gè)
星號(hào),右邊有兩個(gè)空格。所以一行由三部分組成,左中右。
左邊,行號(hào)i與空格數(shù)目的函數(shù)關(guān)系式是:(7 - ((2 * i) - 1)) / 2,當(dāng)i等于1時(shí),前面式子等于3,當(dāng)i等于2時(shí),前面式子等于2
中間,行號(hào)i與星號(hào)數(shù)目的函 數(shù)關(guān)系式是: (2 * i - 1) ,當(dāng)i等于1時(shí),前面式子等于1,當(dāng)i等于2時(shí),前面式子等于3.
右邊,行號(hào)i與空格數(shù)目的函數(shù)關(guān)系式是:(7 - ((2 * i) - 1)) / 2
(hint: for the first half, the rule is 2n-1. record their pattern( the number of their * asterisk and the number of space, then apply to the second half.but the sequence is reverse.)
public class Test {
public static void main(String[] args) {
int n = 7;
int m = (n + 1) / 2; /*m說(shuō)明頭4行應(yīng)怎么畫*/
String[] b = new String[n]; //記錄用set up a Array to memorize the records
for (int i = 0; i < n; i++) {
b[i] = ""; //清空set every head of the element is "" in order to avoid the "NULL" appeared
}
for (int i = 1; i <= m; i++) {
for (int a = 0; a < (n - ((2 * i) - 1)) / 2; a++) {
System.out.print(" ");
b[i - 1] = b[i - 1] + " "; // add to itself
}
for (int a = 0; a < (2 * i - 1); a++) {
System.out.print("*");
b[i - 1] = b[i - 1] + "*";
} //“*”
for (int a = 0; a < (n - ((2 * i) - 1)) / 2; a++) {
System.out.print(" ");
b[i - 1] = b[i - 1] + " ";
}
System.out.print("\n");
}
/*下一段話是反向打印,下面的圖案*/
for (int i = n - m; i > 0; i--) {
System.out.print(b[i - 1]);
System.out.print("\n");
}
}
}
結(jié)果:
*
***
*****
*******
*****
***
*