ccsun3 testjava > cat -n mySecondJava.java 1 // mySecondJava.java -- CopyLeft by tsaiwn@csie.nctu.edu.tw 2 // please compare to p7.c in our C/C++ handouts 3 // Java 程式也是個 class, 按習慣該以大寫開頭, 但不按習慣也是會動... 4 // 何時該寫 static function? 5 // 不是 static 的 function 使用時須依附著 object, 例 x.function(); 6 //*** Pascal Triangle 是用來暸解array很好的例子 7 ////// 8 public class mySecondJava { 9 static int MAXorder = 14; 10 private static void somespace(int k){ 11 if(k<10) System.out.print(" "); 12 else if(k<100) System.out.print(" "); 13 else System.out.print(" "); 14 } 15 public static void main( String p[]) { 16 int i,j,k; 17 int n; 18 int x[][] = new int[MAXorder+1][MAXorder+1]; 19 System.out.print("Generate 巴斯卡三角形, order=?"); 20 n = myScanf(); 21 while( !(3<=n && n<=MAXorder)) { 22 System.out.print(" order must be in 3.." + MAXorder); 23 System.out.print(", order=?"); 24 n = myScanf(); 25 } 26 System.out.println(""); 27 for(i=0; i<=n; i++){ 28 x[i][0]=1; x[i][i] =1; 29 for(j=1; j<= i-1; j++){ 30 x[i][j]= x[i-1][j] + x[i-1][j-1]; 31 } 32 for(j =0; j<=i; j++){ 33 somespace(x[i][j]); 34 System.out.print(x[i][j]); 35 }; 36 System.out.println(""); 37 }; //* for i 38 return; 39 } 40 public static int myScanf(){ 41 int c, ans, i, nc, NEWLINE=10, ZERO= (int) '0', NINE=(int)'9'; 42 int b[] = new int[88]; 43 i=0; 44 try{ 45 c = System.in.read(); // one byte each time 46 while(c != NEWLINE){ 47 b[i++] = c; 48 c = System.in.read(); 49 } 50 nc = i + 1; 51 ans= b[0] - ZERO; 52 for(i=1; i< nc; i++){ 53 if(b[i] NINE) break; 54 ans = ans*10 + b[i] - ZERO; 55 } 56 return ans; 57 } catch(java.io.IOException e){ return 0; } 58 } 59 } ccsun3 testjava > /usr/local/jdk/jdk1.2.2/bin/javac mySecondJava.java ccsun3 testjava > /usr/local/jdk/jdk1.2.2/bin/java mySecondJava Generate 巴斯卡三角形, order=?19 order must be in 3..14, order=?8 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 ccsun3 testjava >