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;
}
}
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:
In that case, if an exception is encountered, your method could return null.
This is another example of the same issue.