public class Yang
{
public static void main(String[] args)
{
int row=Integer.parseInt(args[0]);
int[][] Ragged=new int[row][];
for(int i=0;i<row-1;i++)
Ragged[i]=new int[i+1];//初始化二维数组
for(int i=0;i<=row-1;i++)
{
for(int j=0;j<=i;j++)
{
if(i>=2&&j>=1&&j<i)
Ragged[i][j]=Ragged[i-1][j-1]+Ragged[i-1][j];
else
Ragged[i][j]=1;
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<=i;j++)
System.out.println(Ragged[i][j]);
System.out.println("\n");
}
}
}运行后会出现
Exception in thread "main" java.lang.NullPointerException
at Yang.main(Yang.java:16)

解决方案 »

  1.   


    //使用递归,写起来容易点
    import java.util.*;
    public class Yang {
    public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    while (reader.hasNextInt()) {
    int row = reader.nextInt();
    display(row);
    }
    } public static void display(int m) {
    for (int j = 0; j <= m; j++) {
    for (int i = 0; i <= j; i++) {
    System.out.print(" " + countYang(j, i));
    }
    System.out.println();
    }
    } public static int countN(int n) {
    if (n == 0 || n == 1)
    return 1;
    else
    return n * countN(n - 1);
    } public static int countYang(int m, int n) {
    n = m - n;
    return countN(m) / countN(n) / countN(m - n);
    }
    }
      

  2.   

    主要错误是
    for(int i=0;i<row-1;i++)
    Ragged[i]=new int[i+1];//初始化二维数组 应该是i<row,少循环了一次。后面打印格式还有小问题。
      

  3.   

    应该二维数组的问题,数组要是处理不好经常会出现NullPointerException
      

  4.   

    [code=Java]/**************************杨辉三角*************/
    public class Test {
    public static void main(String[] args) {
    int num=5;
    for(int i=0;i<num;i++){
    for(int j=0;j<=i;j++){
    System.out.print(count(i,j)+"-");
    }
    System.out.print("\n");
    }
    }
    public static int count(int m,int n){
    if(n == 0){ 
    return 1; 
    }else if(m == n){ 
    return 1; 
    }else{
    return count(m-1,n-1)+count(m-1,n);
    }
    }
    }code]
      

  5.   


    public class yanghuisanjiao {
    public static void main(String[] args) {
    int num=5;
    for(int i=0;i<num;i++){
    for(int j=0;j<=i;j++){
    System.out.print(count(i,j)+"-");
    }
    System.out.print("\n");
    }
    }
    public static int count(int m,int n){
    if(n == 0){ 
    return 1; 
    }else if(m == n){ 
    return 1; 
    }else{
    return count(m-1,n-1)+count(m-1,n);
    }
    }
    }
      

  6.   


    // 楊輝三角
    public static void main(String[] args) {
    int m = 10;
    int n = 2 * m + 1; long[][] arr = new long[m][n]; arr[0][m] = 1; for (int i = 1; i < m; i++) {
    for (int j = 1; j < n - 1; j++) {
    arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1];
    }
    } for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
    System.out.printf("%3s", arr[i][j] == 0 ? "  " : arr[i][j]);
    }
    System.out.println();
    }
    }