0

How do you read in data from a text file that contains nothing but chars into a 2d array using only java.io.File, Scanner, and file not found exception?

Here is the method that I'm trying to make that will read in the file to the 2D array.

public AsciiArt(String filename, int nrRow, int nrCol){
    this.nrRow = nrRow;
    this.nrCol = nrCol;

    image = new char [nrRow][nrCol];

    try{
        input = new Scanner(filename);

        while(input.hasNext()){

        }   
    }
}
Winter
  • 3,894
  • 7
  • 24
  • 56

2 Answers2

2

Make sure that you're importing java.io.* (or specific classes that you need if that's what you want) to include the FileNotFoundException class. It was a bit hard to show how to fill the 2D array since you didn't specify how you want to parse the file exactly. But this implementation uses Scanner, File, and FileNotFoundException.

public AsciiArt(String filename, int nrRow, int nrCol){
    this.nrRow = nrRow;
    this.nrCol = nrCol;
    image = new char[nrRow][nrCol];

    try{
        Scanner input = new Scanner(new File(filename));

        int row = 0;
        int column = 0;

        while(input.hasNext()){
            String c = input.next();
            image[row][column] = c.charAt(0);

            column++;

            // handle when to go to next row
        }   

        input.close();
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        // handle it
    }
}
bwalshy
  • 1,096
  • 11
  • 19
  • thanks you, that helped to jog my memory. I've been pouring over different code and sometimes I forgot. – General Antrhax Feb 08 '17 at 02:32
  • Do you not increment `row`? Is it always 0? – kurdtpage Sep 18 '18 at 08:49
  • You increment the row where the comment "// handle when to go to next row" is. I didn't show row being incremented because the OP didn't specify how big the lines are or how they are detecting the end of line. But the solution would be: if all the rows are the same length (i.e. all 7 columns wide), you'd increment the row every 7 columns. If the rows are different lengths (have variable columns), then you'd check if you're at the end of the line – bwalshy Sep 19 '18 at 02:25
0

A rough way of doing it would be:

    File inputFile = new File("path.to.file");
    char[][] image = new char[200][20];
    InputStream in = new FileInputStream(inputFile);
    int read = -1;
    int x = 0, y = 0;
    while ((read = in.read()) != -1 && x < image.length) {
        image[x][y] = (char) read;
        y++;
        if (y == image[x].length) {
            y = 0;
            x++;
        }
    }
    in.close();

However im sure there are other ways which would be much better and more efficient but you get the principle.

fill͡pant͡
  • 1,147
  • 2
  • 12
  • 24