Something with arrays

Discussion in 'Plugin Development' started by vsams14, May 11, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    vsams14

    So I need to have a structured array. That's easy enough:
    Code:java
    1. public class WorldTime {
    2. String name;
    3. boolean locked;
    4. int dawn = 1800;
    5. int day = 12000;
    6. int dusk = 1800;
    7. int night = 8400;
    8. int id;
    9. }


    then I declare the array: WorldTime[] wtime = new WorldTime[3];
    Now if I want to write something into my array, I need to go through each index and set it to its class type (String, Boolean, Integer, etc...), and after this, I should be able to just go and say wtime[0].name = "World";

    or:
    Code:java
    1. tworlds = 3;
    2. for(int x = 0; x==tworlds;x++){
    3. wtime[x].name = new String();
    4. }


    however, every time I try setting the array to something that is not "" or 0 (for ints), I get a nullPointerException, even though I made sure to initialize the indices with "" and 0.

    I cannot understand why this is happening, and would really apreciate help with this problem!
    Thanks!
    vsams14
     
  2. Offline

    Trc202

    While
    Code:
    WorldTime[] wtime = new WorldTime[3];
    does create an array with 3 slots, the array has nothing in it. It just knows it holds 3 of the WorldTime Class.
    You must first initialize each element in your array before you can use it. You can do this by
    Code:
    for(int i = 0; i < wtime.length; i++){
    wtime[i] = new WorldTime();
    }
    Also, you are going to have some problems with
    Code:
        tworlds = 3;
        for(int x = 0; x==tworlds;x++){
        wtime[x].name = new String();
        }
    as x will result in the set (0,1,2,3) A total of four elements (which is out of bounds for your array). I recommend using
    Code:
    for(int x = 0; x < wtime.length; i++)
    instead. x would then result in the set (0,1,2)
     
  3. Offline

    r0306

    vsams14
    Code:
    for(int x = 0; x==tworlds;x++){
    Change that to

    Code:
    for(int x = 0; x<tworlds;x++){
     
  4. Offline

    vsams14

    So I was initializing the wrong parts of the array...
    Thanks for that! Will now plug into code and see what happens!

    It seems to work! Thanks so much for your help!
    vsams14

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 25, 2016
Thread Status:
Not open for further replies.

Share This Page