0

I am trying to create a 2d array using the contents of a text file, however I am unable to return it. It says it cannot find the symbol firstDimension, however I declared it within the method.

import java.io.*;
import java.util.*;

public class Map {
    public static char[][] readFile() {
        try {
            List<String> list = new ArrayList<String>();

            String thisLine = null;
            BufferedReader br;
            br = new BufferedReader(new FileReader("map.txt"));

            while ((thisLine = br.readLine()) != null) {
                list.add(thisLine);
            }

            char[][] firstDimension = new char[list.size()][];
            for (int i = 0; i < list.size(); i++) {
                firstDimension[i] = list.get(i).toCharArray();
            }

            for (int i=0; i < firstDimension.length; i++) {
                for (int j=0; j < firstDimension[i].length; j++) {
                    System.out.print(firstDimension[i][j]);
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return firstDimension;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user506912
  • 69
  • 2
  • 9

1 Answers1

1

firstDimension is declared within your try block hence its scope is that try block. to be able to return it outside the try block, you need to declare it as follows:

public static char[][] readFile() {
    char[][] firstDimension = null;
    try {
        List<String> list = new ArrayList<String>();

        String thisLine = null;
        BufferedReader br;
        br = new BufferedReader(new FileReader("map.txt"));

        while ((thisLine = br.readLine()) != null) {
            list.add(thisLine);
        }

        firstDimension = new char[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            firstDimension[i] = list.get(i).toCharArray();
        }

        for (int i=0; i < firstDimension.length; i++) {
            for (int j=0; j < firstDimension[i].length; j++) {
                System.out.print(firstDimension[i][j]);
            }
            System.out.println();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return firstDimension;
}

In that case, if an exception is encountered, your method could return null.

This is another example of the same issue.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Does this mean that when I edit firstDimension within the try block it will not actually be permanently changed? And thank you. – user506912 Mar 01 '12 at 12:56
  • in the full code I posted, if no exception is raised, firstDimension will contain whatever value you have assigned to it in the try block. If an Exception is raised, it will contain the value it had when the Exception was raised, which could be null or not. – assylias Mar 01 '12 at 12:59