我正在嘗試創建一個圖案列印程式。
我無法以相反的順序列印我的圖案。我知道第二個回圈中有一些邏輯錯誤for,但我無法識別它。
public class test {
public static void main(String[] args) {
int num = 7;
int temp1 = 1;
int temp2 = 1;
for (int i = 1; i <= num / 2; i ) {
for (int j = 1; j <= num - i; j ) {
System.out.print(" ");
}
for (int k = 1; k <= temp1; k ) {
System.out.print(Math.abs(k - temp2));
}
temp1 = 2;
temp2 ;
System.out.println();
}
temp1 = 1;
temp2 = 1;
for (int i = num - (num / 2); i >= 1; i--) {
for (int j = 1; j <= num - i; j ) {
System.out.print(" ");
}
for (int k = temp1; k >= 1; k--) {
System.out.print(Math.abs(k - temp2));
}
temp1 = 2;
temp2 ;
System.out.println();
}
}
}
程式輸出:
0
101
21012
0
101
21012
3210123
預期輸出:
0
101
21012
3210123
21012
101
0
uj5u.com熱心網友回復:
因為您需要列印的圖形由三個部分組成,所以您必須將您的解決方案分成三個單獨的方法。所以測驗它們會更容易。
頂部和底部非常相似。您可以采取的最簡單的方法是僅對底部部分重用相同的代碼,只需進行一個更改:外部的索引for以最大值初始化,并且在迭代的每一步都會遞減(您做對了,但是您我們還更改了內部for回圈,因為您的第一個回圈塊也負責列印中間部分)。
public static void print(int size) {
printTopPart(size);
if (size % 2 == 1) { // middle part will be printed if size is odd
printMiddlePart(size);
}
printBottomPart(size);
}
public static void printTopPart(int size) {
int height = size / 2;
for (int row = 0; row < height; row ) {
// print the white space
for (int i = 0; i < height - row; i ) {
System.out.print(" ");
}
// print the row of numbers
for (int i = 0; i < row * 2 1; i ) {
System.out.print(Math.abs(row - i));
}
System.out.println(); // advance the output to the next row
}
}
public static void printMiddlePart(int size) {
// print the row of numbers
for (int i = 0; i < size; i ) {
System.out.print(Math.abs(size / 2 - i));
}
System.out.println(); // advance the output to the next row
}
public static void printBottomPart(int size) {
int height = size / 2;
for (int row = height - 1; row >= 0; row--) {
// print the white space
for (int i = 0; i < height - row; i ) {
System.out.print(" ");
}
// print the row of numbers
for (int i = 0; i < row * 2 1; i ) {
System.out.print(Math.abs(row - i));
}
System.out.println(); // advance the output to the next row
}
}
main()- 演示
public static void main(String[] args) {
print(7);
}
輸出
0
101
21012
3210123
21012
101
0
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456887.html
上一篇:加載csv并將列添加為for回圈
下一篇:如何在VBA中進行適當的增量?
