2017-07-02 45 views
0

該代碼在註釋行上給出了NullPointerException。我無法找出問題。該代碼爲鋸齒狀數組提供了NullPointerException

package com.lambda.classes; 

import java.util.Random; 

public class Lambda { 

    public static void main(String []args) 
    { 
     int array[][]=new int[5][]; 
     Random r=new Random(); 
     Random r2=new Random(); 
     for(int i=0;i<5;i++){ 
      int x=r.nextInt(10); 
      for(int j=0;j<x;j++) 
      { 
       int y=r2.nextInt(200);//this line gives a null pointer exception 
       array[i][j]=y; 
      } 
     } 

     for (int[] is : array) { 

      for (int i : is) { 
       System.out.print(i+"\t"); 
      } 
      System.out.println(); 
     } 
     Random x=new Random(); 
     System.out.println(x.nextInt(10)); 
     System.out.println(x.nextInt(10)); 
    } 
} 
+1

這是不可能的NPE那裏發生。請分享實際的代碼和完整的異常堆棧跟蹤。 – BackSlash

+0

另請閱讀:[用於創建二維數組的語法](// stackoverflow.com/q/12231453) – Tom

回答

0

在你這段代碼錯誤'array [i] [j] = y;'。 由於它'int數組[] [] = new int [5] [];'

您還需要設置內部陣列的大小。

像這樣的事情

public static void main(String[] args) { 
    int array[][] = new int[5][]; 
    Random r = new Random(); 
    Random r2 = new Random(); 
    for (int i = 0; i < 5; i++) { 
     int x = r.nextInt(10); 
     array[i] = new int[x]; 
     for (int j = 0; j < x; j++) { 
      int y = r2.nextInt(200); 
      array[i][j] = y; 
     } 
    } 
    for (int[] is : array) { 
     for (int i : is) { 
      System.out.print(i + "\t"); 
     } 
     System.out.println(); 
    } 
    Random x = new Random(); 
    System.out.println(x.nextInt(10)); 
    System.out.println(x.nextInt(10)); 
} 
+0

*「您還需要爲內部數組設置大小。」*不在2d數組的初始化期間。 – Tom

+0

更改了循環中第二個大規模init的代碼。 – IgorGudkov

+0

也不需要第二個「Random」對象。 – Tom

0

其實我想實現爲此事交錯數組有啥一些東西初始化數組一樣的點,一個[5] [100],如果我在java聲明中沒有錯,像int數組[] [] = new int [5] [];是完全好的,謝謝你的答案(Y):)

0

現在我已經使它沒有使用額外的空間,好像我可以不喜歡int [5] [100];這樣我可能會使用額外的空間,但由於該初始化點,它可以很容易地用列表的陣列,而不是做.....謝謝你們:)

int array[][]=new int[5][]; 
     Random r=new Random(); 
     for(int i=0;i<5;i++){ 
      int x=r.nextInt(10); 
      array[i]=new int[x]; 
      for(int j=0;j<x;j++) 
      { 
       array[i][j]=r.nextInt(200); 
      } 
     } 

    for (int[] is : array) { 
     for (int i : is) { 
      System.out.print(i+" "); 
     } 
     System.out.println(); 
    }