Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (495)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  Class and array  (Read 4778 times)
0 Members and 1 Guest are viewing this topic.
Offline satchel

Senior Newbie





« Posted 2011-01-17 23:15:34 »

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.

1  
2  
3  
4  
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.

1  
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:

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


Grateful for help!
Offline Mike

JGO Wizard


Medals: 76
Projects: 1
Exp: 6 years


Java guru wanabee


« Reply #1 - Posted 2011-01-17 23:20:05 »

How do you fill the array at the moment?

Mike

My current game, Minecraft meets Farmville and goes online Smiley
State of Fortune | Discussion thread @ JGO
Offline teletubo
« League of Dukes »

JGO Ninja


Medals: 48
Projects: 4
Exp: 8 years



« Reply #2 - Posted 2011-01-17 23:21:12 »

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.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline krasse
« Reply #3 - Posted 2011-01-17 23:47:36 »

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

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



Offline cylab

JGO Ninja


Medals: 49



« Reply #4 - Posted 2011-01-18 10:49:01 »

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

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

Small forum escaping problem here: should read
Quote from: krasse
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())

Mathias - I Know What [you] Did Last Summer!
Offline satchel

Senior Newbie





« Reply #5 - Posted 2011-01-18 13:23:15 »

How do you fill the array at the moment?

Mike

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:
1  
2  
3  
4  
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
Offline SimonH
« Reply #6 - Posted 2011-01-18 13:32:53 »

Fill the array this way;
1  
2  
3  
for (int i = 0; i<10; i++){
            myArray[ i ] = new Person();
        }

People make games and games make people
Offline satchel

Senior Newbie





« Reply #7 - Posted 2011-01-18 14:01:17 »

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:
1  
System.out.println("population: "+myArray.length);


It doesn't give me any numbers. It doesn't even print out the word within "".

Offline cylab

JGO Ninja


Medals: 49



« Reply #8 - Posted 2011-01-18 14:42:03 »

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:
1  
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)

Mathias - I Know What [you] Did Last Summer!
Offline satchel

Senior Newbie





« Reply #9 - Posted 2011-01-18 17:14:22 »

Ok, I can't seem to find the problem.
I'll show you all my code I hvae so far.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
/**
 * @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.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline teletubo
« League of Dukes »

JGO Ninja


Medals: 48
Projects: 4
Exp: 8 years



« Reply #10 - Posted 2011-01-18 17:53:16 »

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 :

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
    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();
        }

Offline satchel

Senior Newbie





« Reply #11 - Posted 2011-01-18 18:35:31 »

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

Thanks for everyones help! Smiley
Offline satchel

Senior Newbie





« Reply #12 - Posted 2011-01-18 19:26:24 »

Just one last question!

How do I delete an element from my array?
1  
myArray[i].splice(i,i);



splice() doesn't seem to work because i'm using a custom array.
Offline SimonH
« Reply #13 - Posted 2011-01-18 19:37:50 »

1  
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.

People make games and games make people
Offline teletubo
« League of Dukes »

JGO Ninja


Medals: 48
Projects: 4
Exp: 8 years



« Reply #14 - Posted 2011-01-18 19:40:19 »

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
1  
 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
1  
 while(myVector.size() != 0){

or
1  
 while(!myVector.isEmpty() ){


Offline satchel

Senior Newbie





« Reply #15 - Posted 2011-01-18 20:21:00 »

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

Senior Newbie





« Reply #16 - Posted 2011-01-18 20:38:05 »

hmm need help with that too Tongue

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

and how do I add elements to the vector in a loop?
Offline SimonH
« Reply #17 - Posted 2011-01-18 20:42:00 »

Now you're just being lazy!

People make games and games make people
Offline satchel

Senior Newbie





« Reply #18 - Posted 2011-01-18 20:57:24 »

Yeah I was 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 Smiley


Offline JL235

JGO Coder


Medals: 10



« Reply #19 - Posted 2011-01-23 15:33:57 »

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.

Offline ReBirth
« Reply #20 - Posted 2011-01-24 04:48:20 »

I second JL235. You can also use more "specific" ArrayList with

1  
List<Person> myArray = new ArrayList<Person>();


so everytime you need your Person class (by get(int) method), there is no need to cast it. ArrayList always returns Object type.

Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #21 - Posted 2011-01-24 19:14:09 »

I second JL235. You can also use more "specific" ArrayList with

1  
List<Person> myArray = new ArrayList<Person>();


so everytime you need your Person class (by get(int) method), there is no need to cast it. ArrayList always returns Object type.
Actually, this just becomes slow casting under the hood. Templates in Java are kind of crap. If you're worried about performance, better to make a subclass of ArrayList that accepts only a certain type of class. Then you can deal with the type casting yourself and make it maximally efficient.

See my work:
OTC Software
Offline cylab

JGO Ninja


Medals: 49



« Reply #22 - Posted 2011-01-24 19:33:59 »

Actually I doubt that his use case will need this kind of performance tuning. In fact I would advise not to worry about performance at all unless you have something working and you are experienced enough to fully understand the implications of certain changes (like synchronized vs unsynchronized collections)

Mathias - I Know What [you] Did Last Summer!
Offline JL235

JGO Coder


Medals: 10



« Reply #23 - Posted 2011-01-24 19:45:58 »

I second JL235. You can also use more "specific" ArrayList with

1  
List<Person> myArray = new ArrayList<Person>();


so everytime you need your Person class (by get(int) method), there is no need to cast it. ArrayList always returns Object type.
Actually, this just becomes slow casting under the hood. Templates in Java are kind of crap. If you're worried about performance, better to make a subclass of ArrayList that accepts only a certain type of class. Then you can deal with the type casting yourself and make it maximally efficient.
Genrics, not templates, don't always require casts (there are ways to avoid them). Casts are also far from slow. There is also no reason why they couldn't be optimized out with runtime tracing (although that is purely speculation). However optimizing your algorithms in order to reduce their time complexity will have a far greater impact on performance.

Your sub-classing technique would make your code less maintainable whilst having a very minor impact on performance (if any).

Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #24 - Posted 2011-01-24 23:22:55 »

I second JL235. You can also use more "specific" ArrayList with

1  
List<Person> myArray = new ArrayList<Person>();


so everytime you need your Person class (by get(int) method), there is no need to cast it. ArrayList always returns Object type.
Actually, this just becomes slow casting under the hood. Templates in Java are kind of crap. If you're worried about performance, better to make a subclass of ArrayList that accepts only a certain type of class. Then you can deal with the type casting yourself and make it maximally efficient.
Genrics, not templates, don't always require casts (there are ways to avoid them). Casts are also far from slow. There is also no reason why they couldn't be optimized out with runtime tracing (although that is purely speculation). However optimizing your algorithms in order to reduce their time complexity will have a far greater impact on performance.

Your sub-classing technique would make your code less maintainable whilst having a very minor impact on performance (if any).
Yes, I meant generics, not templates. Apologies.

Ask Kev his opinion of generics and you'll get much more fire and brimstone than from me. Personally I'm going to stop arguing now, since it's already been done many times before.

Have a look at this:
http://www.facsim.org/node/77
Quote
Before getting into the details, here's the main problems with Java's generics:

At run-time, all generic type information is lost. For example, a Stack <Box> cannot be distinguished (at run-time) from a Stack <Receipt> - they both become just a Stack.
At run-time, all type parameter instances are converted to/from Object references, meaning that there is a high upcast/downcast overhead (not to mention a high boxing-unboxing overhead, if using primitive types) when using generics.
All instances of generic classes have the exact same static members.
It is not possible to throw generic exceptions (generic classes derived from Throwable).

See my work:
OTC Software
Offline princec

JGO Kernel


Medals: 378
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #25 - Posted 2011-01-24 23:48:32 »

I just generified my entire game library Smiley Bliss.

Cas Smiley

Offline ReBirth
« Reply #26 - Posted 2011-01-25 03:04:58 »

I second JL235. You can also use more "specific" ArrayList with

1  
List<Person> myArray = new ArrayList<Person>();


so everytime you need your Person class (by get(int) method), there is no need to cast it. ArrayList always returns Object type.
Actually, this just becomes slow casting under the hood. Templates in Java are kind of crap. If you're worried about performance, better to make a subclass of ArrayList that accepts only a certain type of class. Then you can deal with the type casting yourself and make it maximally efficient.

Thanks for you suggestion. Did you mean create a class which extending ArrayList? can give an example? I've searched it but they don't give code. (sorry for silly question) ;-)

Offline cylab

JGO Ninja


Medals: 49



« Reply #27 - Posted 2011-01-25 12:42:29 »

Just dont bother! Stick to whats working for you and get something done before trying to optimize at this level. You wont get anywhere if you start this now. Trust me: "premature optimization is the root of all evil"

Mathias - I Know What [you] Did Last Summer!
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #28 - Posted 2011-01-25 19:33:14 »

Just dont bother! Stick to whats working for you and get something done before trying to optimize at this level. You wont get anywhere if you start this now. Trust me: "premature optimization is the root of all evil"
Okay, I will agree with this. Just stick with the Vector or whatever that you've got already.

But FYI, here is something like what I was referring to:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public class MonkeyArrayList extends ArrayList
{
    public Monkey get(int i)
    {
        return (Monkey) super.get(i);
    }

    public void add(Monkey m)
    {
        super.add(m);
    }

    //etc.
}

See my work:
OTC Software
Online Riven
« League of Dukes »

JGO Overlord


Medals: 798
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #29 - Posted 2011-01-25 19:39:26 »

Actually, this just becomes slow casting under the hood. Templates in Java are kind of crap. If you're worried about performance, better to make a subclass of ArrayList that accepts only a certain type of class. Then you can deal with the type casting yourself and make it maximally efficient.

But FYI, here is something like what I was referring to:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public class MonkeyArrayList extends ArrayList
{
    public Monkey get(int i)
    {
        return (Monkey) super.get(i);
    }

    public void add(Monkey m)
    {
        super.add(m);
    }

    //etc.
}


You honestly think this is faster?

I don't get it. Generics does exactly the same, except that is doesn't do the cast in the ArrayList, but at the callsite. What you do is moving the cast from the usual callsite into your own (newly created) callsite. For HotSpot it's exactly the same code, while your subclass even adds another level of indirection. I'm stumped.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Pages: [1] 2
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Dwinin (28 views)
2014-09-12 09:08:26

Norakomi (57 views)
2014-09-10 13:57:51

TehJavaDev (73 views)
2014-09-10 06:39:09

Tekkerue (37 views)
2014-09-09 02:24:56

mitcheeb (57 views)
2014-09-08 06:06:29

BurntPizza (44 views)
2014-09-07 01:13:42

Longarmx (27 views)
2014-09-07 01:12:14

Longarmx (34 views)
2014-09-07 01:11:22

Longarmx (34 views)
2014-09-07 01:10:19

mitcheeb (40 views)
2014-09-04 23:08:59
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!