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 3 of 3

Thread: issue with arrays in Java

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default issue with arrays in Java

    Hello there,

    A friend of mine and I are trying to get into Java; I'm mainly a C/C++ programmer, and he is obsessed with PHP and until now we've never been able to collaboratively work on a game project because of opposing languages so we decided to try out Java since it is similar enough to both C++ and PHP to make transitioning rather simple. Anyways to get to the point...

    I'm still learning Java; been at it for about a week and to get my bearings I'm making a very very crude but simple 2D game with a character that moves on the screen and can fire a bullet at the enemy. The problem I'm having is creating multiple instances of the sprites using a sprite pointer and an array.

    in C/C++ it would be something like this:
    int n;
    SPRITE *bullet[n]; then I use a 'for' loop: for(n=0;n<3;n++) and then the function will handle the dirty job of dealing with more than one sprite of the same type without me having to write out the details for each sprite of that type. In C/C++ doing it this way is perfectly legal.

    In Java I seem to have to set it up like this...

    Sprite bullet[]; note the lack of an astericts or the value within the square braces; that confuses me. Whenever I put something in there during the declaration it complains, yet I can call the bullet within the loop,
    for(n=0;n<3;n++)
    {
         bullet[n]...whatever
    }
    Everything looks fine until I compile which gives an error "Exception in thread "main" java.lang.NullPointerException" I assume the error has to do with the fact that there isn't anything inside the square braces during the declaration but it wont let me put anything in them; I get a red squiggly line that says NO.

    I'm using Netbeans and the GTGE library.

    the actual code is here: (I know my Java setup is very C-like. I'm new at Java)
    /***********************************
     **** SIMPLE BATTLES DOCUMENT ****
     ***********************************/
     
    // source package
    package simplebattle;
     
    //JFC
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.net.*;
     
     
    // GTGE
    import com.golden.gamedev.*;
    import com.golden.gamedev.object.*;
     
    // game class
    public class SimpleBattle extends Game {
     
        //Game Variables//
        //background sprites
        Sprite background_image0, background_image1, clouds0, clouds1, cloud_shadow0, cloud_shadow1;
        // character sprites
        AnimatedSprite player;
        AnimatedSprite weapon[]; // <--- here is the problem... I think. It wont let me create multiple instances this way.
                                            // if I leave the square braces empty, I get the ok to compile but get an error on result.
                                            // if I put something in the square braces I get the red line of don't bother.
     /****************************************************************************/
     /****************************** FIREWEAPON **********************************/
     /****************************************************************************/
    public void createWeapon(int n) {
     
        // player's weapon
        for(n=0; n<3; n++){
        weapon[n] = new AnimatedSprite(getImages("resources/ioncannon.png",6,1),0,0);
        weapon[n].setLocation(100, 100);
     
        weapon[n].setFrame(0);
        weapon[n].setAnimate(false);
        weapon[n].setLoopAnim(false);
        weapon[n].setActive(false);
        }
    }
    public void updateWeapon(long t, int n){
     
        double speed = -0.4; // set speed for simplicity
        weapon[n].update(t); // update the weapon
     
        if(weapon[n].isActive()) // if weapon is active, move it.
        {
            weapon[n].move(0, speed*t); // remember t is elapsed time.
        }
        if(weapon[n].getY() <= -32) // if weapon is off screen kill it.
        {
            weapon[n].setActive(false);
        }
    }
    public void fireWeapon(int n){ // call this in Inputs
     
        // set the weapon to active and set its loaction.
        weapon[n].setActive(true);
        weapon[n].setLocation((player.getX()-player.getWidth()/2)+45,player.getY());
    }
    public void renderWeapon(Graphics2D g, int n){
     
        // render the weapon if it is active
        if(weapon[n].isActive())
            weapon[n].render(g);
    }
     /****************************************************************************/
     /******************************* CHARACTER **********************************/
     /****************************************************************************/
     
    public void createPlayeri() {
     
       // setup Player
        Player = new AnimatedSprite(getImages("resources/player24bit6.png",6,1),0,0);//66,68),0,0);
     
       // set player start location// this will change when the select screen is added
        player.setLocation((player.getX()+640)/2, (player.getY()+480)/2);
     
        // set start frame
        player.setFrame(0);
        player.setAnimate(false); // this is false because the animation is static
        player.setLoopAnim(false); // only one frame per pose. why waste overhead?
     
    }
     
    public void updatePlayer(long t){
     
        double speed = 0.25;
     
        player.update(t);
     
        // movements will be placed in INPUT section
        if(keyPressed(KeyEvent.VK_ESCAPE)|| keyPressed(KeyEvent.VK_Q))//exit game
           super.finish();
        // move sprite and update it's frames
        if(!keyDown(KeyEvent.VK_A) ||!keyDown(KeyEvent.VK_D))
            player.setFrame(0);    // normal
         if (keyDown(KeyEvent.VK_S)) 
            player.move(0, speed*t);
         if (keyDown(KeyEvent.VK_W)) 
            player.move(0, -speed*t);     
         if (keyDown(KeyEvent.VK_A)) 
         {
             player.setFrame(2); // bank left
             player.move(-speed*t, 0);
         }
         if (keyDown(KeyEvent.VK_D)) 
         {
             player.setFrame(1);// bank right
             player.move(speed*t, 0);
         }
         // fire weapon
         for(int n=0; n<3;n++)
         if(!weapon[n].isActive()) // if weapon is already on screen don't fire, otherwise fire
         if(keyPressed(KeyEvent.VK_SPACE))
             fireWeapon(n);
     
    }
    public void renderPlayer(Graphics2D g){
     
        player.render(g);
    }
     
     /****************************************************************************/
     /******************************* LEVEL **************************************/
     /****************************************************************************/
    public void createLevel(){
        //set background
        background_image0 = new Sprite(getImage("resources/CanyonVally.jpg"), 0,0);
        background_image1 = new Sprite(getImage("resources/CanyonVally.jpg"), 0,480);
        clouds0 = new Sprite(getImage("resources/Clouds.png"), 0,0);
        clouds1 = new Sprite(getImage("resources/Clouds.png"), 0,480);
        cloud_shadow0 = new Sprite(getImage("resources/Clouds_Shadow.png"), 5,-10);
        cloud_shadow1 = new Sprite(getImage("resources/Clouds_Shadow.png"), 5,-490);
     
    }
    public void updateLevel(long t){
     
        //update the background
        background_image0.update(t);
        background_image1.update(t);
        clouds0.update(t);
        clouds1.update(t);
        cloud_shadow0.update(t);
        cloud_shadow1.update(t);
     
        // move backgroud
        // basically I don't know how to wrap images, so I have two images that warp
        // to each other's location once one image leaves the screen. If A is off screen
        // move to the ass of B. if B is off screen, move to the ass of A.
        background_image0.move(0,-0.1);
        background_image1.move(0,-0.1);
        if(background_image0.getY() <= -480)
        {
            background_image0.setLocation(0,background_image1.getY()+480);
        }
        if(background_image1.getY() <= -480)
        {
            background_image1.setLocation(0,background_image0.getY()+480);
        }
     
        // move foreground
        clouds0.move(0,0.1);
        clouds1.move(0,0.1);
        cloud_shadow0.move(0,0.1);
        cloud_shadow1.move(0,0.1);
        // this is the same setup as the background images with A moving to the ass of B
        // and B moving to the ass of A when either are off screen. Additionally the shadows of 
        // A and B are set to their locations with an offset to create depth.
        if(clouds0.getY() >= 480)
            clouds0.setLocation(0,clouds1.getY()-480);//-480);
     
        if(cloud_shadow0.getY() >= 490)
            cloud_shadow0.setLocation(5,clouds0.getY()-10);//-490);
     
        if(clouds1.getY() >= 480)
            clouds1.setLocation(0,clouds0.getY()-480);//-480);
     
        if(cloud_shadow1.getY() >= 490)
            cloud_shadow1.setLocation(5,clouds1.getY()-10);//-490);
     
    }
    public void renderLevel(Graphics2D g){
        // draw the level to the screen
        background_image0.render(g);
        background_image1.render(g);
        cloud_shadow0.render(g);
        cloud_shadow1.render(g);
        clouds0.render(g);
        clouds1.render(g);
     
    }
     /****************************************************************************/
     /**************************** GAME SKELETON *********************************/
     /****************************************************************************/
     
        // initialize game resources
        @Override
        public void initResources() {
     
            // init level goes first
            createLevel();
     
            // init charscters
            createplayer();
     
           // init bullet (this needs to come before player for layering, I'll do that later)
            for(int n = 0; n<3; n++)
            createWeapon(n);
        }
        // update game functions
        @Override
        public void update(long elapsedTime) {
     
            // level updates
            updateLevel(elapsedTime);
            // player updates 
            updatePlayer(elapsedTime);
            for(int n = 0; n<3; n++)
            updateWeapon(elapsedTime,n);
        }
        // redner graphics to the screen
        @Override
        public void render(Graphics2D g) {
            // Graphics Engine
            g.setColor(Color.LIGHT_GRAY);
            g.fillRect(0, 0, getWidth(), getHeight());
     
            /////////////////////////
            //redner game elements///
            /////////////////////////
     
            // draw level first
            renderLevel(g);
     
            // draw players (should go inside level for layering)
            renderPlayer(g);
     
           // draw bullet (this needs to come before player for layering, I'll do that later)
            for(int n = 0; n<3; n++)
            renderWeapon(g,n);
     
        }
     /****************************************************************************/
     /***************************** START-POINT **********************************/
     /****************************************************************************/
        // main function
        public static void main(String[] args) {
            GameLoader game = new GameLoader();
            game.setup(new SimpleBattle(), new Dimension(640,480), false);
            game.start();
        }
    }
    Last edited by helloworld922; October 8th, 2011 at 09:26 PM.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: issue with arrays in Java

    Imagine you're programming as if every object must go on the heap (a rather strange analogy, but it may make the transition easier). All object variables can be treated more or less like pointers/references.

    Sprite[] bullets = new Sprite[3]; // 3 bullet sprites
    for(int i = 0; i < bullets.length; ++i)
    {
        bullets[i] = new Sprite(); // ... sprite constructor
    }

    note that you don't need to manually call 'delete', the garbage collector will take care of cleanup for you.

  3. #3
    Junior Member
    Join Date
    Oct 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: issue with arrays in Java

    Ahh... that will do it. Thanks a lot.

Similar Threads

  1. Having an issue reading files to create two arrays.
    By ccrosby in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 26th, 2011, 06:47 AM
  2. Issue with setting up different class with arrays
    By D-COD3R in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 4th, 2011, 06:09 PM
  3. Java and db2 connection issue
    By sukhpal48806 in forum JDBC & Databases
    Replies: 2
    Last Post: March 1st, 2011, 12:07 PM
  4. java.util.ConcurrentModificationException Issue
    By joshuaa in forum Collections and Generics
    Replies: 1
    Last Post: December 2nd, 2010, 04:41 PM
  5. java graphics2d issue
    By nana-j13 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 15th, 2010, 03:49 PM