2016-02-23 147 views
-1

注:數組構造拋出NullPointerException異常

我已經準備好了文章「什麼是NPE和如何解決它。」 然而,這篇文章並沒有解決特定的數組問題,我懷疑這是我的代碼中的錯誤來源。

這是構造一個UPC代碼(12位)作爲一個字符串的INT []數組(必須使用的charAt()和getNumericValue。然而,它拋出的NullPointerException在作爲是構造的程序。

public class UPC { 

    private int[] code; 

    public UPC(String upc) { 
     int[] newUPC = new int[12]; 
     char currentChar; 
     for (int i=0; i<upc.length();i++) { 
      currentChar = upc.charAt(i); 
      code[i] = Character.getNumericValue(currentChar); 
    } 
} 

public static void main (String[] args){ 

    // call static method to display instructions (already written below) 
    displayInstructions(); 

    // While the string entered is not the right length (12 chars), 
    // tell the user to enter a valid 12-digit code. 
    Scanner scn = new Scanner(System.in); 
    // Declare string and read from keyboard using Scanner object 
    // instantiated above 
    String str = scn.nextLine(); 
     if (str.length()!=12) { 
      System.out.println("Please Enter a Valid 12-Digit Code"); 
     } else { 
      System.out.println("You are good"); 
     } 

    // Create a new UPC object, passing in the valid string just 
    // entered. 
    UPC ourUPC = new UPC(str); 
+1

您還沒有申報代碼[] –

+1

你不初始化'code' – Eran

+0

你的'code'數組沒有初始化。你應該做'int [] code = new code [12];'或者那個效果。或者你可能打算在循環內執行'newUPC [i]'。 –

回答

0

之前使用這個數組code你應該初始化它是這樣的:

private int[] code = new int[12]; 

還是在構造函數是這樣的:

private int[] code; 
    public UPC(String upc) { 
    code = new int[12]; 
1
private int[] code; 

爲空,你必須創建它。

private int[] code = new int[12]; 

或多個動態:

public UPC(String upc) { 
     code = new int[upc.length()]; 
} 
相關問題