-3

i've been trying to programm a game called Sokoban the last few days. The levels of the game are simple .txt files you can swap. I've already read the .txt file by using BufferedReader but have problems with saving it to an 2-dimensional char array because the number of rows and columns are different each level. Someone told me to make use of charAt but how do i do that.

Sokobanlevel format (http://www.sokoban-online.de/help/sokoban/level-format.html)

Hope you can help me. Thanks.

String file = "...";
BufferedReader br = Files.newBufferedReader();
String line = null;
int rows = file.length;
int cols = file[0].length;
char[][] room = new char [rows][cols];          
while ((line = br.readLine()) != null) {
            System.out.println(room[rows][cols]);
        }
4
  • Use an arraylist. Or just use a CSV reader library. That's probably easier. Commented Dec 1, 2016 at 22:05
  • Possible duplicate of convert string to arraylist <Character> in java Commented Dec 1, 2016 at 22:05
  • @LucasKot-Zaniewski In theory it is yes, but I don't know if the OP will get it. Commented Dec 1, 2016 at 22:06
  • Thanks for answering that fast. I'll try using the arraylist for now. Cuz I've been programming for about one and a half week now, i don't know about CSV reader library yet. Commented Dec 1, 2016 at 22:15

2 Answers 2

0

Without knowlege about the number of lines in the file you need to read everything from the file first to determine the number of lines. This would be easiest, if you use a List<char[]> to store char arrays for each line.

You could easily write something with the same functionality as a one-liner in java 8 though:

File fl = new File(file);
char[][] array = Files.lines(fl.toPath()).map(String::toCharArray).toArray(char[][]::new);
Sign up to request clarification or add additional context in comments.

Comments

0

You can initialize 2D arrays so that each row has a different number of columns:

char[][] c = new char[7][];
c[0] = new char[5];
c[1] = new char[3];
//etc

1 Comment

The problem is that i cant write numbers in the [ ] cuz levels in txt-files could have the measure 3x3, 4x7 or something else. So i have to create a char Array for levels which are swapable and i dont know the measures.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.