Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: [Solved] Null Pointer Exception :: Switch statement not working.

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default [Solved] Null Pointer Exception :: Switch statement not working.

    Hi,

    First post here and pretty new to Java, so thanks in advance for your help in located what I'm sure is going to be a simple mistake. I am trying to write a basic function that loads a .txt file and turns it into objects with coordinates on the map. I have tested nearly all of the function and it appears to function properly, but when I add the "final piece" the switch statement that assigns objects my draw level function keeps getting a null pointer error which has to mean that my switch statement isn't setting all the object array properly.

    // set the number of objects back to zero
    numberofobjects = 0;
    // reads the text in the file based on what level the player is in
    file = Gdx.files.internal("levels/level" + level + ".txt");
    // Use a string to store the file information to prevent overhead of streaming the file multiple times during this function
    String fileinfo = file.readString();
    // searches through the string to find out the number of objects needed
    for(int objectcount = 0; objectcount < fileinfo.length(); objectcount++){
      if(fileinfo.codePointAt(objectcount) != 0)
        numberofobjects++;  // if its  an object then count up.
    }
    starttime = System.currentTimeMillis();
    acceleration = new Vector2(0, 0);
    if(level == 1){
      // set X and Y to the top left of the screen
      int x = 0;
      int y = Gdx.graphics.getHeight()-64;
      // resize the objects array to the number of objects in the current level
      objects = new Object[numberofobjects];
      // integer to track how many objects have been set so far
      int currentobject = 0;
      // loop through the entire string which contains all object information for the level
      for(int loop = 0; loop < fileinfo.length(); loop++){
      char temp = fileinfo.charAt(loop);
      switch(temp){
        case 0: break; // blank space
        case 1: objects[currentobject] = new Object(0, new Vector2(x, y)); currentobject++; break; // tree
        case 2: break;           
        case 3: objects[currentobject] = new Object(1, new Vector2(x, y)); currentobject++; break; // rock
        case 4: objects[currentobject] = new Object(3, new Vector2(x, y)); currentobject++; break; // water
        case 'X': position = new Vector2(x, y); break;                                     // smiley
        case 'O': objects[currentobject] = new Object(2, new Vector2(x, y)); currentobject++; break; // star
      }
      x += 64;
      if(x == Gdx.graphics.getWidth() || x > Gdx.graphics.getWidth()-64){
        x = 0;
        y -= 64;
      }
    }

    Exact error is java.lang.NullPointerException and it occurs at

    public void drawlevel(){
      drawbackground(grasstile);
      currenttime = System.currentTimeMillis();
      batch.begin();
      for(int loopcontrol = 0; loopcontrol < numberofobjects; loopcontrol++){
        switch(objects[loopcontrol].type){
          case 0: batch.draw(treetile, objects[loopcontrol].position.x, objects[loopcontrol].position.y); break;
          case 1: batch.draw(rocktile, objects[loopcontrol].position.x, objects[loopcontrol].position.y); break;
          case 2: batch.draw(startile, objects[loopcontrol].position.x, objects[loopcontrol].position.y); break;
          case 3: batch.draw(watertile, objects[loopcontrol].position.x, objects[loopcontrol].position.y); break;
        }
      }
      font.draw(batch, ""+((currenttime - starttime)/1000f)+" seconds", 10, Gdx.graphics.getHeight()-10);
      batch.end();
    }

    So the error would probably be in the assignment (my first code) since this draw function is looping through all objects but finds a nullpointer or what I'm assuming is an object with no value.

    Thanks again to anyone who can spot my error of my ways.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Null Pointer Exception :: Switch statement not working.

    Welcome. When you get an exception thrown, it is helpful to include, as well as what you already did, the full stack trace of the exception, and the specific line of code the exception is occurring on (posting the line is helpful, because exception on line x only helps if we know what line x is).
    For example, just saying the null pointer is in the drawlevel() method doesn't tell us enough. In your drawlevel() method, batch could be null, objects could be null, objects[loopcontrol] could be null, objects[loopcontrol].position could be null, font could be null, Gdx could be null, and Gdx.graphics could be null. So, it's hard for us to pinpoint what exactly is null without you pointing out the exact line.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Dec 2013
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Null Pointer Exception :: Switch statement not working.

    My apologies. The entire stack of errors is

    java.lang.NullPointerException
    at lesshardtofind.me.mygdxgame.ThisGame.drawlevel(Thi sGame.java:444) (line 444 is the line where switch(objects[loopcontrol].type) is called)
    at lesshardtofind.me.mygdxgame.ThisGame.gameloop(This Game.java:222) (line 222 is where drawlevel() is called)
    at lesshardtofind.me.mygdxgame.ThisGame.render(ThisGa me.java:467) (line 467 is where gameloop() is called)
    at com.badlogic.gdx.backends.andriod.AndriodGraphics. onDrawFrame(AndriodGraphics.java:499)
    at andriod.opengl.GLSurfaceView$GLThread.run(GLSurfac eView.java:1240)

    none of these point to the real issue which is my switch statement. The error arrives when trying to access the objects array but the error exists in my assignment.

    I'm not getting the right behavior from the way I'm trying to get each individual character out of the string and create an object based on its value.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Null Pointer Exception :: Switch statement not working.

    Ok, well either objects is null, or objects[loopcontrol] is null (I would guess the latter). Check to make sure you are adding objects to the array. You must have not filled up the array all the way. Empty slots in an array of Objects will be filled with null values.
    The first thing you need to do is put in some print statements or something to tell you what values are being used in the switch statement. Should blank spaces have an object associated with them?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Junior Member
    Join Date
    Dec 2013
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Null Pointer Exception :: Switch statement not working.

    I figured it out. The issue was with

    for(int objectcount = 0; objectcount < fileinfo.length(); objectcount++){
      if(fileinfo.codePointAt(objectcount) != 0)
        numberofobjects++;  // if its  an object then count up.
    }

    This was supposed to increase the number of objects if it didn't encounter a 0 unfortunately it always increased the number of objects. This would end up with way more objects than needed and since I only would assign 61 in level 1 the drawlevel would attempt to access the other 400 something and crash.

    .codeAt(index) returns an int value of Unicode of the char (same as ASCII for 0-127) so instead of != 0 it should have been != 48.
    Secondly I didn't account for the fact that .txt files would have '\n' escape sequences that would qualify as != '0'.

    The new function looks like
    for(int objectcount = 0; objectcount < fileinfo.length(); objectcount++){
      if(fileinfo.charAt(objectcount) == '1' ||
         fileinfo.charAt(objectcount) == 'O' ||
         fileinfo.charAt(objectcount) == '2' ||
         fileinfo.charAt(objectcount) == '3')
      numberofobjects++;  // if its  an object then count up.
    }

    which is unfortunate that I will need to add another or statement for all 20 objects or more that will be in the final game, but it at least gets around the fact that I don't know every escape sequence and unwanted char that java may interpret out of a .txt file.

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Null Pointer Exception :: Switch statement not working.

    You can improve the look of that if statement with a helper method.
    Something like this:
    for(int objectcount = 0; objectcount < fileinfo.length(); objectcount++){
      if(doesCharEqual(fileinfo.charAt(objectcount)))
      numberofobjects++;  // if its  an object then count up.
    }
    ...
    public boolean doesCharEqual(char val) {
    	char[] options = new char[]{'0','1','2','3'};
    	for(char opt : options) {
    		if(opt==val)
    			return true;
    	}
    	return false;
    }

    This way you can add new OR conditions later by simply adding to the char array, instead of writing a new OR statement. You can also use this functionality elsewhere, if you need to, without having to rewrite it (just call the method).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. The Following User Says Thank You to aussiemcgr For This Useful Post:

    lesshardtoofind (December 11th, 2013)

Similar Threads

  1. Need Help with Null Pointer Exception
    By kendraheartt in forum What's Wrong With My Code?
    Replies: 6
    Last Post: July 23rd, 2012, 02:20 PM
  2. [SOLVED] Null Pointer Exception
    By wltrallen2 in forum Object Oriented Programming
    Replies: 7
    Last Post: May 27th, 2012, 10:21 AM
  3. Null Pointer exception
    By Demetrius82 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: June 2nd, 2011, 07:32 PM
  4. Null Pointer Exception Help!!
    By puzzledstudent in forum What's Wrong With My Code?
    Replies: 5
    Last Post: November 11th, 2010, 06:46 PM
  5. [SOLVED] Null Pointer Exception
    By musasabi in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 11th, 2010, 09:25 PM