Class and array

So what I am trying to do is loop through an array filled with variables which are defined by my own class.

The class itself contains variables like integers and booleans, and I want to add other stuff later.


class Person {
        int life = 100;
        boolean alive = true;
    }

and then I want to create an array which i’m going to fill with variables from my class.


static Person myArray[];

Now here i’m starting to get problems.

I’ve tried to fill the array with variables from my clsas through a loop but without success.

And I’m guessing that’s why I cant loop through my array like this:


for(int i=0; i<myArray.length; i++){
                if(myArray[i].alive == true){
                    ...
                }

Grateful for help!

How do you fill the array at the moment?

Mike

for what you have posted there’s nothing wrong with your code . Post more code and be more specific on what kind of errors you’re facing then we can help you.

NullPointerException when you access myArray.length => forgot to initialize array (new Person[arraySize])

NullPointerException when you access myArray[i].alive => forgot to fill array with references to Persons (myArray[i] = new Person())

Small forum escaping problem here: should read

Well that is one of the thing i’m not sure if i’m doing right.

Now i’m doing a for loop which each turn creates a new object and use the push function to add it to the array:


for (int i = 0; i<10; i++){
            Person person = new Person();
            myArray.push(person);
        }

But the compiler says “Cannot find symbol” at the push function

Fill the array this way;


for (int i = 0; i<10; i++){
            myArray[ i ] = new Person();
        }

Great that seems to work!

But now i’m wondering how to get information from each element.
when I try to print out a variable like this:


System.out.println("population: "+myArray.length);

It doesn’t give me any numbers. It doesn’t even print out the word within “”.

It does work this way. In your program the line is probably just not executed, because it is never reached (due to some wrong if statement, a return too much or something similar)

Ok, I can’t seem to find the problem.
I’ll show you all my code I hvae so far.


/**
 * @author Satchel
 */


package testlife;
//import java.util.Random;
//import java.util.Timer;
import java.util.*;

class Person {
        int life = 100;
        boolean alive = true;
        }


public class Main {
    
    public static int rounds = 0;
    public static int delay = 100; //milliseconds
    
    public static Random generator = new Random();   

    public static int startPop = 10;    
    private static Person myArray[];

    public static void main(String[] args) {
        // TODO code application logic here
        

        System.out.println("alive : " + startPop);
                       
        for (int i = 0; i<startPop; i++){
            myArray[i] = new Person();  
        }

        System.out.println("pop: "+myArray.length);

        //System.out.println(generator.nextInt(10)); //Generates a random nr between 0 - 10

        while(myArray.length != 0){
            for(int i=0; i<myArray.length; i++){
                if(myArray[i].alive == true){
                    //System.out.println("HP = "+monster.life);
                    System.out.println("Population = "+i);
                    System.out.println("Round = "+rounds);
                    rounds = rounds +1;
                    myArray[i].life = myArray[i].life - 1;

                    System.out.println("");

                    //Search for food
                    int nr = generator.nextInt(10);
                    if(nr > 6){
                        myArray[i].life = myArray[i].life + 2;
                    }

                    //Mate

                    //Dead or alive
                    if(myArray[i].life <= 0){
                        myArray[i].alive = false;
                        //monster.splice(i,i);
                    }

                    //Slows down the process to make it more readable
                    try {
                        Thread.sleep(delay);
                    }
                    catch (Exception e) {}

                }
            }
            
        
        }
    }

}



All I get is just a successful run when I run the code.

You don’t get a succesfull run . You get a null pointer exception on line 34 . Read carefully your ouptput.

You have not initialized your array . your code should look like this :



    public static void main(String[] args) {
        // TODO code application logic here
         
 
        System.out.println("alive : " + startPop);
                      
        myArray = new Person[startPop]; //Initialize your array !! this will allocate startPop null-initialized Persons.
  
        for (int i = 0; i<startPop; i++){
            myArray[i] = new Person(); 
        }

sigh I had another project as main project which ran when i compiled…

Thanks for everyones help! :slight_smile:

Just one last question!

How do I delete an element from my array?


myArray[i].splice(i,i);

splice() doesn’t seem to work because i’m using a custom array.

myArray[ i ]=null;

That way the GC will tidy up. You’ll have to check for null entries when you’re scanning the array.
If you want to change the size of the array, make a new (bigger or smaller) array and copy the values across.

you can’t “remove” an element from you array .
You can set this element to null, but still, your array.lenght will be the same .
You should have a look to the class Vector, it might do what you expect, but keep in mind that using a native array (the ones you’re using) is the fastest way .

By the way, this will never be false


 while(myArray.length != 0){

unless you initialized your array with 0 elements, that is
public static int startPop = 0; (which would make no sense)

With a Vector you can query, for exemple


 while(myVector.size() != 0){

or


 while(!myVector.isEmpty() ){

hmm i think a vector is more suitable for what I want so i’m gonna change everything to a vector now.

hmm need help with that too :stuck_out_tongue:

so how do I create a vector? Defining and initialization.

and how do I add elements to the vector in a loop?

Now you’re just being lazy!

Yeah I was :stuck_out_tongue:

Sorry! Was just staring at one website which didn’t help me enough.

Google is your friend ^^

It’s starting to work as I want it to now :slight_smile:

I’d advise an ArrayList over a Vector, it should be faster (Vector’s are synchronized).

Secondly, your array usage looks a lot like your trying to write JavaScript (the use of array.push and array.splice). Just to clarify, Java and JavaScript are entirely unrelated (so things like arrays work differently). They only share the ‘Java’ name due to a marketing deal.