0

I have a series of character arrays storing level data for a game named LEVEL_1, LEVEL_2 etc. I have to make the program advance to the next level when complete, and so I made a string

levelString = ("LEVEL_" + nextLevelNumber)

When I try to then use

advanceToLevel(levelString);

to advance to the next level array it obviously does not work because array and string are incompatible.

Is there a way to make it call the array by string value, or have I missed a simpler way to advance to the next level without an if statement for each level?

I'm quite new to Java, so it needs to be simple.

Edit: this question is not a duplicate. I am asking how to advance to the next array, having tried to use string concatenation with a variable. I am looking for an alternative solution.

M. Finch
  • 1
  • 1
  • You are probably looking for an array of levels. Doing this kind of weird string lookup seems like a code-smell. – mako-taco May 24 '16 at 02:43
  • That's why I'm trying to find an alternative solution. I just need to be able to call advanceToLevel(LEVEL_2); when the first level is complete, and advanceToLevel(LEVEL_3); after that. The arrays in question are 2 dimensional character arrays that store the location of walls, player, ghosts etc in a pacman game. – M. Finch May 24 '16 at 02:47
  • im suggesting that all of your levels be put in another array, like `Level[] levels = {LEVEL_1, LEVEL_2, LEVEL_3};` and `int currentLevelIndex = 0`. You cam access the current level via `Level getCurrentLevel() { return levels[currentLevelIndex];` and advance to the next level with `void advanceLevel() { currentLevelIndex++;}` – mako-taco May 24 '16 at 02:52
  • It IS a duplicate. Look into that duplicate question: You cannot construct a string and use the string as name of variable. You just need to have a array (or `List` etc) of level, so you can access your level 0 by `levels[0]` and level 1 by `levels[1]` (assuming `levels` being an array of "character array") – Adrian Shum May 24 '16 at 03:06
  • Thank you. I did not understand exactly what the other question was getting at it seems. I will make an array of levels, and this seems like a far better solution. Thank you all! – M. Finch May 24 '16 at 03:19

0 Answers0