I'm working on an assignment were we have to get characters from a file and store it in a 2D array. We're not allowed to post our code anywhere so i'll use a psuedocode. Let me know if it's not clear.
fillFromFile (parameters){
Scanner input = new Scanner(new FileReader(fileName));//from parameter
char[][] returnChar = new char[parm][parm];//gotten from parameters
String line = input.nextLine();
String[] spliter = null;
int count = 0;
while (input.hasNextLine and count < row) {
line = input.nextLine();
spliter = line.split(" ", 2);
count++;
for (int i = 0; to returncharLength; increment i) {
for (int j = 0; to returnchar[i]Length; increment j) {
returnChar[i][j] = spliter[0].charAt(j);
}
}
}
return returnChar;
}
If I print out from the method directly, the correct values are shown but we can't print from methods. There's a toString() method to handle that already.
The 2D array being returned are just the last characters. eg, if this is the expected value,
r e
r e
o p
b n
this is what is being returned
b n
b n
b n
b n
I've tried doing a deep copy, before and after returning it but there's no difference. My deep copy method looks like this:
private static char[][] deepCopy (char [][] data){
char [][] newArray = new char [//][//];
for (int i = 0; i < length i++) {
for (int j = 0; j < colLength; j++) {
newArray[i][j] = data[i][j];
}
}
return newArray;
}
I think the while loop is overwriting all the data before exiting. How can I fix this?
If something is not clear, please let me know and i'll edit my question.
I've also tried returning the 2d array at different parts of the method
This is an example of how I'm using the returned 2d array
variableX = new ClassName (2dArrayThatWasReturned); return variableX;
-> variableX is of type ClassName and the constructor accepts a 2d array -> The 2D array that was passed will have it values assigned to an instance 2d array. The instance 2d array is the one that gets printed
The problem is that your loop:
for (int i = 0; to returncharLength; increment i) { for (int j = 0; to returnchar[i]Length; increment j) { returnChar[i][j] = spliter[0].charAt(j); } }
will override the whole array because you go from row 0
to returnchar.length
, every time. Instead you need to fill only the next row after the last one. You can rewrite your for
loops as follow:
for (int r=0; r<returnchar.length; r++) { // "r" for row
String line = input.nextLine();
String[] splitter = line.split(" ", 2);
for (int c=0; c<returnchar[r].length; c++) { // "c" for column
returnchar[r][c] = splitter[c];
}
}
This is how to print a pretty Array 2D:
for (char[] x : returnChar) {
System.out.println(Arrays.toString(x));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.