我想用Java寫一個捕捉用戶整數(假設數據有效)的程序,然後根據整數的大小輸出菱形形狀,即用戶輸入5,輸出將是:使用循環的Java ascii藝術
--*--
-*-*-
*---*
-*-*-
--*--
到目前爲止,我有:
if (sqr < 0) {
// Negative
System.out.print("#Sides of square must be positive");
}
if (sqr % 2 == 0) {
// Even
System.out.print("#Size (" + sqr + ") invalid must be odd");
} else {
// Odd
h = (sqr - 1)/2; // Calculates the halfway point of the square
// System.out.println();
for (j=0;j<sqr;j++) {
for (i=0;i<sqr;i++) {
if (i != h) {
System.out.print(x);
} else {
System.out.print(y);
}
}
System.out.println();
}
}
剛剛輸出
--*--
--*--
--*--
--*--
--*--
任何ID eas,我在考慮減少h
的價值,但那隻會產生鑽石的左手邊。
您能否向我解釋一下Math.abs()函數的作用,我是否認爲它給出了任何數字的正值?我已經向您的代碼添加了評論,以表明我明白髮生了什麼。 – Mike
你說得對,邁克,這正是它所做的。 –