如何读取文本文件并返回带有数据的网格对象



我要创建一个名为Grid createGrid(String filename)的工厂方法,该方法从filename指定的文本文件中读取数据,并返回一个包含数据的Grid对象。如果数据不是有效的,它应该抛出ioe异常

private char[][] showBoard; //2D array that holds the board
public static char[] gems = { 'r', 'g', 'b', 'y' };
//constructor to initialize the instance variables
public Grid(int row, int cols) {
this.row = row;
this.cols = cols;
showBoard = new char[row][cols];
}
// method to fill the showBoard with random gems
public void fillBoard() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < cols; j++) {
showBoard[i][j] = getRandomGem();
}// end of inner for loop
} // end of outer for loop
}// end of fillBoard method
//method to choose random Gem
public static char getRandomGem() {
int choice = (int) (Math.random() * gems.length);
return gems[choice];
} //end of get random gem method
public String toString() {
String result = "Grid with " + row + " rows and " + cols + " columns";
for (int i = 0; i < row; i++) {
result += "n";
for (int j = 0; j < cols; j++) {
result += showBoard[i][j];
}
}
return result;
}  // end of toString
//Starting of phase 2
public Grid(char[][] someGrid) {
this.row = someGrid.length;
this.cols = someGrid[0].length;
this.showBoard = someGrid;
}
public char[][] createGrid(String filename) throws IOException {
this.row = 1;
this.cols = 1;
char[][] returnGrid = new char[this.row][this.cols];
Scanner input = new Scanner(new BufferedReader(new FileReader(filename)));
try {
while (input.hasNextLine()) {
for (int i = 0; i < returnGrid.length; i++) {
String line = input.nextLine();
for (int j = 0; j < returnGrid[i].length; j++) {
returnGrid[i][j] = line.charAt(j);
}
}// end of outer for loop
} // end of while loop
return returnGrid = new char[row][cols];
} catch (Exception e) {
System.out.println(e);
} // end of catch
return returnGrid = new char[row][cols];
}// end of try

样本输出:

yr
by
bb
rr
java.io.IOException: No dimensions to 
readjava.io.IOException: The size values were not numeric!
java.io.IOException: There was not enough rows! Saw 5 need 10 java.io.IOException: There was not enough colums. Saw 2

这些应该是相同的:

rryryb
yybgbg
yrrbrb
yyryrr

您的问题就在这里。您仅将数组的大小设置为1,1this.row=1;this.cols=1;您需要定义数组的大小。

我很快就把它拼在了一起。它将满足您的需求。

public static void main(String[] args) throws FileNotFoundException {
BufferedReader input = new BufferedReader(new FileReader("test.txt"));
//get list of all the lines in file as char[]'s
List<char[]> chars = input.lines().map(String::toCharArray).collect(Collectors.toList());
//Find the longest line to bound 2d array
int columns= chars
.stream()
.max(Comparator.comparing(array -> array.length))
.get()
.length;
//get number of lines to bound 2d array
int rows = chars.size();
char[][] grid = new char[rows][columns];
int i = 0;
for (char[] array : chars) {
int j = 0;
for (char c : array) {
grid[i][j] = c;
j++;
}
i++;
}

//      for (int a = 0; a < size; a++) {
//          for (int b = 0; b < max; b++) {
//              System.out.print(grid[a][b]);
//          }
//          System.out.println();
//      }
}

您还可以考虑只使用Collections(List<>(,而不必担心设置数组边界。您可以简单地从返回列表

List<char[]> chars = input.lines().map(String::toCharArray).collect(Collectors.toList());

调用并打印出您的网格,方法是循环使用它,而不是转换为2d数组。

最新更新