Zacharias Hortén
Zacharias Hortén

Reputation: 179

Read .txt file and store in 2-D char array java

I am kind of stuck. How do I get this to work or are there a better way? Please give code examples.

public char[][] charmap = new char[SomeInts.amount][SomeInts.amount];
public void loadMap() throws IOException{
    BufferedReader in = new BufferedReader(new FileReader("map1.txt"));
    String line = in.readLine();
    while (line != null){
        int y = 0;
        for (int x = 0; x < line.length(); x++){

            //Error
            charmap[x][y] = line[x];
            //
        }
        y++;
    }
}

Upvotes: 1

Views: 3067

Answers (3)

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11950

Try this.

char[][] mapdata = new char[SomeInts.amount][SomeInts.amount];

public void loadMap() throws IOException{
    BufferedReader in = new BufferedReader(new FileReader("map1.txt"));
    String line = in.readLine();
    ArrayList<String> lines = new ArrayList<String>();
    // Load all the lines
    while (line != null){
        lines.add(line);
    }
    // Parse the data
    for (int i = 0; i < lines.size(); i++) {
        for (int j = 0; j < lines.get(i).length(); j++) {
            mapdata[j][i] = lines.get(i).charAt(j);
        }
    }
}

Hope this helps.

Upvotes: 1

assylias
assylias

Reputation: 328608

The syntax line[x] is reserved for arrays. A String is not an array. You could use the String#charAt method and write:

charmap[x][y] = line.charAt(x);

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213243

Use String.charAt(int) to fetch character from strings..

Upvotes: 1

Related Questions