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);