-1

Note:

I had already ready the article "What Is NPE and How to Fix it." However the article did not address in particular arrays, which I suspect is the source of error in my code.

This is a program to construct a UPC code (12-digit) as a int[] array from a String (must use charAt() and getNumericValue. However it throws the NullPointerException at the constructor as is.

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);
Zhanwen Chen
  • 1,295
  • 17
  • 21

2 Answers2

1
private int[] code;

is null. you have to create it:

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

or more dynamic:

public UPC(String upc) {
      code = new int[upc.length()];
}
nano_nano
  • 12,351
  • 8
  • 55
  • 83
0

Before using this array code you should initialize it like this:

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

Or in constructor like this:

   private int[] code;
   public UPC(String upc) {
     code = new int[12];
Abdelhak
  • 8,299
  • 4
  • 22
  • 36