简体   繁体   中英

Java - Generate a series of possible coordinates

I'm sorry for the poor wording of the question, but it is the best way I can think of asking this question.

I've initialised a Hashmap (hm) and I'm wanting to use it to store some objects called LandPlots which take x and y coordinates when being called.

Example:

hm.put(new LandPlot(0,0),0); will create a LandPlot at '0,0'

hm.put(new LandPlot(0,1),1); will create a LandPlot at '0,1'

I want to do this with a loop that will go and create enough 'LandPlot' objects to fill an 8x6 'Game board'.

I've tried doing this with the following loop:

for (x = 0; x < 9; x++) {
        for (y = 0; y < 7; y++) {
            hm.put(new LandPlot(x, y), i);
            System.out.println(hm.values());
            i++;
        }
    }

(Where 'x','y' and 'i' are all initialised as '0')

Now, I'm certain of two things:

1) What I'm after should be stupidly simple; I'm sure that I've done something simialr before for picture manipulation in Jython with loops, but I cannot for the life of me remember a term to properly describe it, thus making it hard to find the info I'm looking for online.

2) I'm super new to Hashmaps, and I doubt that hm.values() is the proper way of quickly showing whether or not it has worked.

If there is any more info I can provide, let me know.

Thanks in advance, Doug.

You are storing LandPlot as key and not as value. Try hm.put(i, new LandPlot(x,y)); instead.

All good now, thanks guys.

I combined the info from both answers, and ended up with this loop:

for(y = 0; y < 6;  y++)
    {
          for(x = 0; x < 8; x++)
          {
                hm.put(i, new LandPlot(x, y));
                System.out.println(hm.get(i));
                i++;
        }
    } 

And, after I created getters for x and y , I Overrode toString() in LandPlot to return:

return ("Land Plot at "+LandStore.getX()+","+LandStore.getY());

Thanks again,

Doug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM