-3

I am making a game in Java. I want to be able to check whether a level has been previously visited. I came up with this:

public class LevelTracker {

  boolean depth1visited = false;
  boolean depth2visited = false;
  // ..
  boolean depth100visited = false;


  private boolean LevelTracking() {
    if (Dungeon.depth == 1) {
      depth1visited = true;
    }
    if (Dungeon.depth == 2) {
      depth2visited = true;
    }
    // ..
    if (Dungeon.depth == 100) {
      depth100visited = true;
    }
  }
}

In my situation, each depth must be checked independently since any level might be accessed from any other level. So this:

if (depth > deepestdepth) {
  deepestdepth = depth;
}

won't work in my situation. Unless I'm wrong, which is possible. I am, as you can probably tell, a novice at this.

What is a better way to do this? Could a for loop be used in this situation?

mvw
  • 5,075
  • 1
  • 28
  • 34

1 Answers1

1

Use arrays, which can be addressed by index. This can replace all your ifs and your 100 separate variables.

boolean[] depthVisited = new boolean[100];  // default values: false

Then you can access the array by calculating an index.

depthVisited[Dungeon.depth - 1] = true;  // 0-based index

No for loop is necessary.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Ok, cool. I really wasn't sure if I could even apply an array to this kind of problem. I thought (why, I don't know) that I couldn't apply it to this particular problem. – user5352515 Sep 25 '15 at 21:30