class calling kinda problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Narutodono
    New Member
    • Nov 2009
    • 6

    class calling kinda problem

    Code:
    for (int i=0; i<5; i++)                // for loop for creating a background of tiles
    {
      x=10; 
      
      Graphics g = canvas.getGraphics();           // call Tile to draw a tile
      Tile[] tile = new Tile[10];                  // intialise tile
      tile[i] = new Tile(1,x,y);             // a new tile for every i
      tile[i].Draw(g);                       // draw it
      x=x+50;                           //change x to move next square along	
    }


    this is supposed to create a line along the X axis of squares that is in thge class Tile but it only creates 1 the for loop worksand in theory the x should go 10 60 110 an have at least 3 squares but i dont know why it doesnt work any help is greatly appreciated.
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    You are initialising the tiles-array inside your loop, so you are initialising them 5 times! That makes no sense. You should put that line outside the loop and if you only want 5 squares (the counter "i" in the for-loop), you should set the array size to 5 and not 10!
    Also methods start with lowercase, not uppercase, so you should use "Tile.draw( )" instead of "Tile.Draw( )".
    Also x is reset every time to 10 at the beginning of the loop, but you want x to count up, so put it outside the loop! That's why you get all 5 tiles drawn exactly over each other, because the coordinates are the same in every loop.

    Anyway, you don't need the array if you can forget the tile-object after drawing.
    So what you want is probably following:
    Code:
    int x=10;
    for (int i=0; i<5; i++) // for loop for creating a background of tiles
    {
       Graphics g = canvas.getGraphics(); // call Tile to draw a tile
       Tile tile = new Tile(1, x, y); // a new tile for every i
       tile.draw(g); // draw it
       x += 50; // increase x-coordinate to move next square along 
    }
    By the way:
    It is a very good programming style to make a comment after every line, as you did.

    Comment

    Working...