Java Question

java.lang.NullPointerException appearing for no reason

I have made a program inside of which, there is a specific method that makes sure that all of the objects in an array that point to null point to a blank space. For some reason, whenever I run the code, it gives me a java.lang.NullPointerException.

I understand what a NullPointerException is, which is why I added the if statement, so that it wouldn't give the error, but it still does

Code:

public class TextGraphics {
public static void main(String[] args) {

displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}

}

class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;

public displaySize() {

}

public displaySize(int screenX, int screenY) {

sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}

public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;

}

public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}

public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
for (int b = 0; b < indent; b++) {
next++;
if(rarray(size)[next].equals(null) )
{
System.out.print( rarray(size)[next] + " ");
rarray(size)[next] = " ";
}
System.out.print( rarray(size)[next] + " ");

}
System.out.println("/n");
}

}

}

Answer

first problem used .equals(null) instead of == null

second problem your code throws a arrayoutofindex because your next++ was in the wrong for loop

finally your new line character was wrong its \n not /n corrected code

    public class TextGraphics {
    public static void main(String[] args) {

        displaySize size = new displaySize(5,5);
        displaySize.output(5,3,size,"H");
        displaySize.run(size);
    }

}

class displaySize {
    public static int indent;
    public static int sizeX = 0;
    public static int sizeY = 0;

    public displaySize() {

    }

    public displaySize(int screenX, int screenY) {

        sizeX = screenX;
        sizeY = screenY;
        indent = sizeX;
    }

    public static void output(int x, int y, displaySize size, String print) {
        rarray(size)[x + y * size.sizeX] = print;

    }

    public static String[] rarray(displaySize size) {
        String [] display;
        return display = new String[sizeX * sizeY];
    }

    public static void run(displaySize size) {
        int next = 0;
        for (int i = 0; i < sizeY; i++) {
            next++;
            for (int b = 0; b < indent; b++) {



                if(rarray(size)[next]==(null) )
                {
                    rarray(size)[next] = " ";
                    System.out.print( rarray(size)[next] + " ");

                }
                System.out.print( rarray(size)[next] + " ");
                }


            System.out.println("\n");
        }
    }



}
Comments