How to write a java code in this pattern nested for loop

2007-07-12 5:32 am
1
131
13531
1357531
135797531
1357531
13531
131
1
更新1:

Both can not run

更新2:

hmtsorno ty so much but if i wan it become diamond shape ?how

回答 (4)

2007-07-13 1:02 pm
✔ 最佳答案
// the solution idea is from looking at absolute number
// e.g. Graph abs(x) in which x is from -4 to 4
// the inner loop can use the same logic as the outer loop,
// but the logic now is more intuitive
int numOfOddNumber = 5;
for(int i=(numOfOddNumber-1)*-1;i < numOfOddNumber;i++){
int currentNumber = (numOfOddNumber - Math.abs(i)-1)*2+1;
String oneRow = Integer.toString(currentNumber);
for(int j=currentNumber-2; j >= 1 ; j=j-2){
oneRow = Integer.toString(j) + oneRow + Integer.toString(j);
}
System.out.println(oneRow);
}
2007-07-14 2:28 pm



圖案的對稱性質亦展現在Java程式之中:




圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/digitpattern01.gif




執行範例:




圖片參考:http://i206.photobucket.com/albums/bb265/a048042l/digitpattern02.gif




原碼下載:



Source code可從Sendspace.com下載 ⇒ DigitPattern.java



編譯:



javac DigitPattern.java



執行:



java DigitPattern


參考: 個人經驗
2007-07-12 6:23 pm
pls try following code:

public class GenOddNumSeq
{ public static void main( String[] args )
{ GenTeam( Integer.parseInt( args[ 0 ] ) );
}
public static void GenTeam( int piTeam )
{ int i = 1;
for ( i = 1; i < piTeam; i++ )
GenLine( i );
for ( ; i > 0; i-- )
GenLine( i );
}

public static void GenLine( int piLine )
{ int i = 1;
for ( i = 1; i <= piLine; i++ )
System.out.print( iGenOdd( i ) );
for ( i -= 2 ; i > 0; i-- )
System.out.print( iGenOdd( i ) );
System.out.println( );
}

public static int iGenOdd( int iNum )
{ return ( iNum * 2 ) - 1;
}
}


OK?
2007-07-12 5:51 am
參考以下範例,
.................
String strresult;
for(i=0;i<noofline_maxdigit;i++){
strresult="";
for(j=0;j<=i;j++){
strresult = strresult + Integer.ToString(2*j+1);
}
for(j=0;j<=i-1;j++){
strresult = strresult + Integer.ToString(2*j+1);
}
System.out.println(strresult);
}
for(i=0;i<noofline_maxdigit-1;i++){
strresult="";
for(j=i;j>=0;j--){
strresult = strresult + Integer.ToString(2*j+1);
}
for(j=i-1;j>=0;j--){
strresult = strresult + Integer.ToString(2*j+1);
}
System.out.println(strresult);
}
...........
參考: me


收錄日期: 2021-04-23 17:07:30
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070711000051KK04707

檢視 Wayback Machine 備份