lordchancellor lordchancellor - 1 year ago 74
Java Question

Populating a Boolean Array in Java

As a fairly green Java coder I've set myself the hefty challenge of trying to write a simple text adventure. Unsurprisingly, I've encountered difficulties already!

I'm trying to give my Location class a property to store which exits it contains. I've used a boolean array for this, to essentially hold true/false values representing each exit. I'm not entirely convinced that

a) this is the most efficient way to do this and

b) that I'm using the right code to populate the array.

I would appreciate any and all feedback, even if it is for a complete code over-haul!

At present, when instantiating a Location I generate a String which I send through to the setExits method:

String e = "N S U";

In the Location class, setExits looks like this:

public void setExits(String e) {
if (e.contains("N"))
bexits[0] = true;
else if (e.contains("W"))
bexits[1] = true;
else if (e.contains("S"))
bexits[2] = true;
else if (e.contains("E"))
bexits[3] = true;
else if (e.contains("U"))
bexits[4] = true;
else if (e.contains("D"))
bexits[5] = true;

I'll be honest, I think this looks particularly clunky, but I couldn't think of another way to do it. I'm also not entirely sure now how to write the getExits method...

Any help would be welcome!

Answer Source

Is there any reason why you are doing this with Strings and aren't passing in booleans, i.e.

public void setExits(boolean N, boolean E, boolean S, boolean W, boolean U, boolean D) 

Or having setters?

public void setNorthOpen(boolean open)
  bexits[4] = open;

Secondly, why are you storing the exits as an array of booleans, it's a small finite set, why not just

boolean N,S,E,W,U,D;

As then you don't need to keep track of which number in the array each direction is.


This is a correct answer (if not completely optimal like that of @gexicide) but I fully encourage anyone to look at the other answers here for an interesting look at how things can be done in Java in different ways.

For future reference

Code which works belongs on Code Review, not Stack Overflow. Although as @kajacx pointed out, this code shouldn't -in fact- work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download