Having some trouble with a static array

I've been trying to make a game for fun/practice, and I tried to use a method to make the program shorter. Here's the method, and the relevant variables:

public static int itemCount;
public static String[] itemName = new String[15];
public static String[] itemDesc = new String[15];
public static void additem (String name, String description){
    for(int i = 0; i < itemCount; i++){
        if(itemName[i].equals(name)){
            break;
        }else if(i == (itemCount - 1)){
            itemName[itemCount] = name;
            itemDesc[itemCount] = description;
            itemCount++;
            break;
        }
    }
}

I'm getting a NullPointerException error on line 6 of the above snippet, which to my understanding means it's unable to read itemName, despite being able to read itemCount just fine. Does anyone know how to fix this problem, or some alternative (not too advanced; I'm still a beginner) I can use?

Edit: For clarification: in the main program, itemCount = 1, and I've initialized itemName[0].

Answers


You array item is null, just invert the equals like the code below and it will solve your problem:

 if(name.equals(itemName[i])){

You need to fix up your looping inside the addItem method. It is simpler to iterate through all the elements added so far, check if this new name is already in the itemName array, and just exit the method if so (using return; for a void method).

static int itemCount = 0;

static void addItem(String name, String desc) {
    // check to see if the name is already in the array
    for (int i=0; i < itemCount; i++) {
        if (name.equals(itemName[i])) return; //exits method        
    }
    // now just add the item
    itemName[itemCount] = name;
    itemDesc[itemCount] = desc;
    itemCount++;
}

Need Your Help

spilt string with 2 or more possibilites with action script 2

actionscript-2

I am trying to simplify a baseURL string with action script 2.