Reputation: 21
I have a .txt file which a I want to convert into a 2d array of chars. The only error I get is that linea.toCharArray(); cannot be converted into a 2d array
public static char[][] llegeixPuzle(String nomPuzle)throws IOException{
BufferedReader input = new BufferedReader(new FileReader(nomPuzle));
String linea = "";
char[][] 2dBoard = new char[0][0];
while((linea = input.readLine()) != null){
2dBoard = linea.toCharArray();
}
return 2dBoard;
}
My .txt file contains the following
TCADRACT
PPPPPPPP
········
········
········
········
pppppppp
tcadract
Upvotes: 0
Views: 89
Reputation: 1099
First, you have to count your rows
and column
, basically you have 8 rows and 8 columns.
So first we have created the char [][]
array so that we will save our data
int totalRows = 8;
int totalColumn = 8;
char[][] myArray = new char[totalRows][totalColumn];
Creating the file that we will read
File file = new File(nomPuzle);
Starting with the try-catch construct we iterate through our file for every iteration we create a new char[] chars
array after that we iterate through the chars[]
array and we add our data to our array myArray[i][j] = chars[j];
try(Scanner scanner = new Scanner(file)) { //try with resources
for (int i = 0; scanner.hasNextLine() && i < totalRows; i++) {
char[] chars = scanner.nextLine().toCharArray();
for (int j = 0; j < totalColumn && j < chars.length; j++) {
myArray[i][j] = chars[j];
}
}
}
FULL CODE
public static void main(String[] args) throws IOException {
char [][] returnedArray = llegeixPuzle("YOURFILE.TXT");
System.out.println(Arrays.deepToString(returnedArray));
}
public static char[][] llegeixPuzle(String nomPuzle)throws IOException {
int totalRows = 8;
int totalColumn = 8;
char[][] myArray = new char[totalRows][totalColumn];
File file = new File(nomPuzle);
try(Scanner scanner = new Scanner(file)) { //try with resources
for (int i = 0; scanner.hasNextLine() && i < totalRows; i++) {
char[] chars = scanner.nextLine().toCharArray();
for (int j = 0; j < totalColumn && j < chars.length; j++) {
myArray[i][j] = chars[j];
}
}
}
return myArray;
}
}
OUTPUT
[[T, C, A, D, R, A, C, T], [P, P, P, P, P, P, P, P], [·, ·, ·, ·, ·, ·, ·, ·], [·, ·, ·, ·, ·, ·, ·, ·], [·, ·, ·, ·, ·, ·, ·, ·], [·, ·, ·, ·, ·, ·, ·, ·], [p, p, p, p, p, p, p, p], [t, c, a, d, r, a, c, t]]
Upvotes: 3