Accessing a class through an arrayList in another class

edited March 2017 in Questions about Code

I have a class that I want to be accessed by another class and only in there. (in a little game) So, my structure is that I have the main program that calls the class Tile and then everything runs over Tile. In Tile, I want to access the class Carrots (that are supposed to be collected by the player). I used normal Arrays so far for the other things that get displayed in Tile, but I want the carrots to be removed after collision and read about ArrayLists for doing so. However, I cant even get it to show the carrots once I have them in an ArrayList.. could you help me with that? I hope that once I know how to implement them in the first place, Ill figure how to remove objects from the ArrayList.

class Tile
{
  Platform[]platforms = new Platform[3];
  ArrayList<Carrots>karotten;

  float posX=0;
  float posY=0; 
  float Width=0;
  float Height=0;
  float speedX = 1;

  Tile (float x, float y, float w, float h)
  {
    posX = x;
    posY = y;
    Width = w;
    Height = h;

    for (int i=0; i<platforms.length; i++) {
      platforms[i] = new Platform(100+random(100)+i*150, height-70, 30, 40);
    }

    karotten=new ArrayList<Carrots>();
    for (int i=0; i<karotten.size(); i++) {
    karotten.add(new Carrots(random(150), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(150,250), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(250,350), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(350,450), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(450,550), random(height-200, height-150), 10, 20));
    }
  void display()
  {
    for (int i=0; i<platforms.length; i++) {
      platforms[i].drawPlatform(posX);
    }

    for(int i=0; i<karotten.size(); i++) {
      Carrots carrots = (Carrots) karotten.get(i);
      carrots.displayCarrots(posX);
    }
}

Answers

  • Remove that for loop on line 24.

  • edited March 2017

    Thanks a lot!! But I dont understand why. And also, I need to use for-loops for the collision detection. Dont they look like that for ArrayLists? The collision detection works, but the removal still doesnt.

     boolean checkCarrots(float x, float y, float w, float h)
       {  
       for (int i=0; i<karotten.size(); i++)
       {
         if (karotten.get(i).carrotsCollected(x,y,w,h,posX)) {
           return true;
         }
       }
       return false;
       }
    
      void checkCarrots()
       {
       for (int i=karotten.size(); i>0; i--) {
       if (checkCarrots) {
       karotten.get(i).remove(i);
       return;
       }
       }
       }
    
  • The initial size the ArrayList is 0.

  • It works now, thank you so much for your help!

Sign In or Register to comment.