Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Can't figure this out, I've created a simple class of coordinates to hold x and y ints. In another class I have a global array of Coordinates declared called "ords". In my loop I'm adding Coordinates. When trying to use method getX() and getY() from the Coordinates class in my getaction method, I get a null pointer exception. I'm sure the objects are not null, but I still can't figure out whats going wrong. Any help appreciated.

   import java.util.*;

   import org.w2mind.net.*;

   import java.io.Serializable;


   public class ConorsMind  implements Mind 
  {
     int [][] surroundings = new int [12][16];
     Coordinates [] ords = new Coordinates [192];

int currentX;
int currentY;

//====== Mind must respond to these methods: ==========================================================
//  newrun(), endrun()
//  getaction()
//======================================================================================================

public void newrun()  throws RunError 
{
}


public void endrun()  throws RunError
{
}

private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++)
    {
    for(int z = 0; z < 12; z++)
        {
            surroundings[z][i] = someArray[counter];
            if(surroundings[z][i] ==0) {
                currentX=z;
                currentY=i;
            }
            else if(surroundings[z][i]==4){
                ords[n]= new Coordinates(z,i);
                n++;
            }

            System.out.print(z+" , "+i+": "+surroundings[z][i]);
            System.out.println();
            counter++;
        }
    }
}

public Action getaction ( State state )
{ 
String  s = state.toString();        
String[]    x = s.split(",");
int act =MinerWorldUpdated.NO_ACTIONS;
int counter = 0;
int [] surround = new int [192]; 
//in this way user will have ability to see what surrounds him
for(int i = 11; i < 203; i++)
    {
    surround[counter] = Integer.parseInt(x[i]);
    counter++;
    }
    formTwoDimmensional(surround);


int [] response = new int [x.length];
for(int i = 0; i < x.length; i++)
    {
    response[i] = Integer.parseInt ( x[i] );
    }

    System.out.println("Current position: "+currentX+" ,"+currentY);


    int coalX=ords[0].getX();
    int coalY=ords[0].getY();

    System.out.println("Coal position: "+coalX+" ,"+coalY);


    if(coalX != 0 && coalY !=0)
    {
        if(coalX>currentX)
        {
            act=MinerWorldUpdated.ACTION_DOWN;
        }
        else if(coalY<currentY)
        {
            act=MinerWorldUpdated.ACTION_LEFT;
        }
        else if(coalX<currentX)
        {
            act=MinerWorldUpdated.ACTION_DOWN;
        }
        else if(coalY<currentY)
        {
            act=MinerWorldUpdated.ACTION_LEFT;
        }

    }

String a = String.format ( "%d", act );

return new Action ( a );         
}

    }

    class Coordinates implements Serializable 
    {
private int x;
private int y;

public Coordinates(int x1, int y1)
{
    x=x1;
    y=y1;
}

public int getX(){
    return x;
}

public int getY(){
    return y;
}

}

Error is as follows: java.lang.NullPointerException at ConorsMind.getaction(ConorsMind.java:146)

The error is stemming from the following two lines:

int coalX=ords[0].getX();
int coalY=ords[0].getY(); 

I am calling formTwoDimensional() and its working perfectly, the ords objects are being created successfully and are not null as testing with System.out.println(ords[n].getX()) is printing the expected result when placed in my else if(surroundings[z][i]==4) block.

share|improve this question
 
Please indicate where exactly you get the exception. –  Thilo Dec 19 '12 at 1:27
 
Share your stacktrace. –  Smit Dec 19 '12 at 1:28
4  
Learning to debug NullPointerExeptions is one of the most important things you can learn as a java programmer. Look at your stack trace to see which line is throwing the exception. Then look at every object that is de-referenced on that line and check whether or not it's null. You cannot call a method on an object that is null. That's what you're trying to do. –  jahroy Dec 19 '12 at 1:31
1  
The error doesn't really help us, since we don't know what line of code, line 146 corresponds to. –  TimoteeTheCodeMonkee Dec 19 '12 at 1:34
1  
That string will cause your code to crash. Have a look at it. There's no 4 in it, so after you parse that into your int array, and you pass it to your formTwoDimensional(), the else if block will never get called. So what happens then? ords[0] (or any other ords[n]) will never get set, and hence your program will crash. –  TimoteeTheCodeMonkee Dec 19 '12 at 2:26
show 9 more comments

closed as too localized by Brian Roach, jahroy, Bohemian, bensiu, NullPointerException Dec 19 '12 at 4:34

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

3 Answers

You need to make sure that you're calling formTwoDimensional(). If you are indeed, then it's likely that you're not ever getting into your else if block in the nested for loop, and hence ords[0] is never actually being set, so when you try to access it, it's null.

The other thing to do, if you don't want to post the rest of your code, is to add some more debugging code. See below the boolean zero_pos_set. But make sure that you see the print "Zero pos set" before your program crashes. My bet is that you don't.

public class ConorsMind  implements Mind 
{
    int [][] surroundings = new int [12][16];
    Coordinates [] ords = new Coordinates [192];
    boolean zero_pos_set = false;


    private void formTwoDimmensional(int [] someArray)
    {
        int counter = 0;
        int n=0;
        for(int i = 0; i < 15; i++) {
            for(int z = 0; z < 12; z++) {
                surroundings[z][i] = someArray[counter];
                if(surroundings[z][i] ==0) {
                    currentX=z;
                    currentY=i;
                } else if(surroundings[z][i]==4) {
                    zero_pos_set = true;
                    ords[n]= new Coordinates(z,i);
                    n++;
                }
                counter++;
            }
        }
    }

    public Action getaction ( State state ) {
        if(zero_pos_set) {
            System.out.println("Zero pos set!");
        }
        int coalX=ords[0].getX();
        int coalY=ords[0].getY();
        System.out.println("Coal position: "+coalX+" ,"+coalY);
        return new Action ( a );         
    }
}
share|improve this answer
 
I didn't include the full code because its too large, but yes I am calling formTwoDimensional() and the objects are being initialised successfully. Printing out ords[0].getY(); in my else if(surroundings[z][i]==4) block is working fine, I'm getting the correct results but it does not work at int coalX=ords[0].getX(); in my getaction method –  derpyderp Dec 19 '12 at 1:38
1  
Are you calling formTwoDimensional() on the same instance of ConorsMind that you're calling getAction() on? And are you sure that you're calling formTwoDimensional() before getAction()? –  TimoteeTheCodeMonkee Dec 19 '12 at 1:42
 
No getaction is called first and then formTwoDimensional() is called from within getaction. After formTwoDimensional() is called, int coalX and int coalY are initiated. –  derpyderp Dec 19 '12 at 1:47
 
Not according tot he code you've posted. How can people help if you don't show the actual code? –  jahroy Dec 19 '12 at 1:48
 
Sorry, I'll post the original now. –  derpyderp Dec 19 '12 at 1:49
show 1 more comment

Based on all of the debugging information posted within this thread, it seems that in your getaction() function, you're being passed some state, that doesn't contain 4.

When you parse this information and pass it to formTwoDimensional(), you will never reach the else if block, and so ords[0], or any other ords[n], will never be set.

As a result, when you try to access ords[0] back in your getaction() function, you actually get null, and hence your NullReferenceException.

share|improve this answer
 
+1 for having the patience to stick with this despite the fact that the OP made it very difficult to help. –  jahroy Dec 19 '12 at 2:31
 
Thanks. I remember way back when, when I was first learning to program, and how much I appreciated the help, when struggling to understand some concepts, etc. –  TimoteeTheCodeMonkee Dec 19 '12 at 2:33

It's an order of operations issue.

If you never make a call to formTwoDimmensional(), you'll never initialize anything inside of your array. Be sure you're calling that first.

The actual NPE happens when you attempt to call coalX=ords[0].getX();, which won't work if ords[0] is null.

share|improve this answer
 
... or if getX() is null (since it's being assigned to a primitive int). –  jahroy Dec 19 '12 at 1:43
 
Then it will return 0. It's the instance of Coordinates that's null. –  TimoteeTheCodeMonkee Dec 19 '12 at 1:44
 
Oops... you're right. Didn't notice that getX() returned a primitive int. My bad. –  jahroy Dec 19 '12 at 1:45
 
It is called. Reposted the original code above if you want to have a look. –  derpyderp Dec 19 '12 at 1:59

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