2016-02-23 152 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()]; 
} 
相关问题