Как прочитать текстовый файл и вернуть объект сетки с данными - PullRequest
0 голосов
/ 23 октября 2019

Я должен создать фабричный метод с именем 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 Ответ

0 голосов
/ 23 октября 2019

Ваша проблема лежит здесь. Вы только устанавливаете размер массивов равным 1,1 this.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();
//      }

    }

Вы также можете просто использовать Коллекции (Список <>), чтобы не беспокоиться об установке границ массива. Вы можете просто вернуть список из вызова

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

и распечатать свою сетку, пройдя по ней, вместо преобразования в двумерный массив.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...