2016-06-20 81 views
-3

這是一個二維數組,從用戶的價值把它給了我NullPointerException錯誤! btw我是初學者,所以如果你能讓它更加詳細。感謝二維陣列上的錯誤

public static void main(String[] args) { 
    java.util.Scanner scan = new Scanner(System.in); 
    int[][] matrix = null; 
    System.out.println("Enter " + matrix.length + " rows and " + 
      matrix[0].length + " columns: "); 

    for (int row = 0; row < matrix.length; row++) { 

     for (int column = 0; column < matrix[row].length; column++) { 

      matrix[row][column] = scan.nextInt(); 

     } 
    } 
} 

錯誤

Exception in thread "main" java.lang.NullPointerException 
+2

'它給了我運行時間error' - 這錯誤做你會得到,堆棧跟蹤是怎麼樣的? –

+3

我想你會得到一個NullPointerException,因爲你還沒有正確初始化矩陣數組。 – Gildraths

+3

http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – Tom

回答

0

你應該來定義矩陣的大小一樣,對於爲例:

public static void main(String[] args) { 
    java.util.Scanner scan = new Scanner(System.in); 
    int n, m; 
    n = scan.nextInt(); 
    m = scan.nextInt(); 
    int[][] matrix = new int[n][m]; 
    System.out.println("Enter " + matrix.length + " rows and " 
      + matrix[0].length + " columns: "); 

    for (int row = 0; row < matrix.length; row++) { 

     for (int column = 0; column < matrix[row].length; column++) { 

      matrix[row][column] = scan.nextInt(); 

     } 
    } 
} 
+0

感謝您的幫助,但我想用戶輸入長度 – Sohaib

+0

我編輯我的帖子,您可以使用它 –

+0

,解決我的問題謝謝Youcef我真的很感激 – Sohaib