楊輝三角

 

  1. package com.test1;  
  2.  
  3. import java.io.*;  
  4.  
  5. public class model1 {  
  6.  
  7.     /**  
  8.      * @param args  
  9.      *            楊輝三角  
  10.      */ 
  11.     public static void main(String[] args) {  
  12.         // TODO Auto-generated method stub  
  13.         try {  
  14.             System.out.print("請輸入需要顯示的行數:");  
  15.             BufferedReader br = new BufferedReader(new InputStreamReader(  
  16.                     System.in));  
  17.             String s = null;  
  18.             s = br.readLine();  
  19.             int n = Integer.parseInt(s);  
  20.             Demo1 d = new Demo1();  
  21.             d.test1(n);  
  22.         } catch (Exception e) {  
  23.             // TODO: handle exception  
  24.             e.printStackTrace();  
  25.         }  
  26.     }  
  27. }  
  28.  
  29. class Demo1 {  
  30.     public void test1(int n) {  
  31.  
  32.         int i, j;  
  33.         int m;  
  34.         int[][] arry;  
  35.         arry = new int[n][n];  
  36.         for (i = 0; i < n; i++) {  
  37.             for (m = 0; m < n - i; m++) {  
  38.                 System.out.print(" ");  
  39.             }  
  40.             for (j = 0; j < n; j++) {  
  41.  
  42.                 if (j == 0 || j == i) {  
  43.                     System.out.print("1");  
  44.                     System.out.print("  ");  
  45.                     arry[i][j] = 1;  
  46.                 } else {  
  47.                     if (j < i) {  
  48.                         arry[i][j] = arry[i - 1][j - 1] + arry[i - 1][j];  
  49.                         System.out.print(arry[i][j]);  
  50.                         if (arry[i][j] > 10) {  
  51.                             System.out.print(" ");  
  52.                         } else {  
  53.                             System.out.print("  ");  
  54.                         }  
  55.                     } else {  
  56.                         System.out.print(" ");  
  57.                     }  
  58.                 }  
  59.             }  
  60.             System.out.println();  
  61.         }  
  62.     }  
  63. }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章