2014-10-05 53 views
-3

我試圖建立一個N×N矩陣,它將用0和1打印。它顯示了在代碼中沒有錯誤,但是當我運行我的代碼,我得到線程「main」 java.lang.NumberFormatException線程「main」中的異常java.lang.NumberFormatException:null是什麼意思?

例外:空

我不知道如何解決它。

public class LargestRowColumn { 

    public static void printMatrix (int n){ 

     for (int i = 1; i <= n; i++) 
     { 
      for (int j = 1; j <= n; j++) 
      { 
       System.out.println((int)(Math.random() * 2)+ " "); 
      } 

      System.out.println("\n"); 
     } 
    } 


    public static void main(String[] args) { 

     System.out.println("Enter a number"); 
     String Matrix = null; 
     int n = Integer.parseInt(Matrix); 

     System.out.print(n); 
    } 

} 

回答

3

這意味着你正在試圖解析null爲int:

String Matrix = null; 
int n = Integer.parseInt(Matrix); 

你可能想從用戶那裏得到一些信息。

+0

哈哈謝謝我認爲我已經失去了我的頭腦仍然是一個noob在Java – 2014-10-05 18:04:26

0

你正試圖轉換null整數

String Matrix = null; 
Integer.parseInt(Matrix); // here is exception 

如果你想從用戶的輸入,然後這樣做:

int matrix=new Scanner(System.in).nextInt(); 
printMatrix(matrix); // print matrix 
0

如果你想從用戶那裏得到輸入,掃描儀類是最好的辦法。要使用它,寫這樣的代碼:

import java.util.Scanner;    //since JAVA SE 7 

public class AnyClass{ 

    public static void main(String[] a){ 
    Scanner scan = new Scanner(System.in); 
         //telling Scanner Class to proceed with input Stream 

    System.out.println("Enter a number"); 
    int n = scan.nextInt();    //getting a number from the user 

    } 
} 

以及編寫好的代碼,嘗試使用嘗試塊捕捉異常(S)。

你可以在try塊中將你的代碼放在本例中的main()方法中,後面跟一個或多個catch塊來捕獲異常並處理它。

相關問題