Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have been doing this homework assignment for some time now and cannot figure out how to fix this null pointer error I am getting. I think it is an issue with int[] a in my code and it not being initialized before i call on a.length:

class target{

    int arraySearch(int a[], int target){
        for(int index = 0; index < a.length; index++){
            if(a[index] == target)
                return index;
        }
        return -1;
    }

    public void main(String[] args) {
        target t = new target();
        int test1[] = {15,20,5,11};
        int test2[] = {15,20,7,11};
        System.out.println("Testing arraySearch with target = 5 and array of 15,20,5,11: " + t.arraySearch(test1,5));
        System.out.println("Testing arraySearch with target = 5 and array of 15,20,7,11: " + t.arraySearch(test2,5));
    }
}

If you guys could please help me and explain what is wrong that would be greatly appreciated. I am having this error on other parts of my homework and would like to fix them myself. All advice is appreciated.

share|improve this question
1  
Just as a heads up for the future, java classes should be capitalized like so Target –  Drew Galbraith Apr 4 '14 at 6:30
    
make your class public and main method static –  ruhungry Apr 4 '14 at 6:32
7  
Note that main should be defined as static. Other than that, the given code snippet runs fine as does not produce a NullPointerException. –  Mureinik Apr 4 '14 at 6:32

1 Answer 1

up vote 0 down vote accepted

I don't get any null pointers. Just changed the signature to public static void main ... Runs fine for me: Testing arraySearch with target = 5 and array of 15,20,5,11: 2 Testing arraySearch with target = 5 and array of 15,20,7,11: -1

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.