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

Displaying values from mysql db - fetch_object() error

php

I am submitting values from the form into mysql db. After, I am performing a select query to try to grab those previously inserted values and display their result. I am using a while loop to iterat...

How do I prompt for input from an SSIS package?

sql ssis

I want to be able to have a sql query in my DTSX package and I want to be able to have some sort of prompt to update the value of a null column. See what I have below:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.