Samkayoki
Samkayoki

Reputation: 89

Copying a text file into a 2D char array in java

I'm working on reading a text file that contains an 5x6 character big ascii image. Here's what i've done so far:

  ...    
  Scanner fileReader = null;
  try{
     File file = new File(fileName);
     fileReader = new Scanner(file);
     int offset = 0;

     char [][] pic = new char[5][6];

     while (fileReader.hasNextLine()){
        for (int u = 0; u < row; u++){
           for (int i = 0; i < col; i++){
              String line = fileReader.nextLine();
              pic[u][i] = line.charAt(offset++);
           }
        }
        return pic;
     }
     fileReader.close();
  }
  catch(Exception e){
     System.out.println(e.getMessage());
  }...

This gives me a "no line found" message. I'm wondering if the scanner i use to ask the user the name of the file is a part of the problem. Here's what that looks like:

  System.out.println("Hello! I load files.");
  System.out.println("Please, enter file name:");
  Scanner reader = new Scanner(System.in);
  String fileName = reader.nextLine();

I've tried to close the reader after but it didn't change anything. Any help is much appreciated.

Upvotes: 0

Views: 73

Answers (2)

Amjad Nassar
Amjad Nassar

Reputation: 22

Scanner fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
    String line = fileReader.nextLine();
    pic[i] = line.toCharArray();
    i++;
}
fileReader.close();

I tried it with seuqnce and worked:

 Scanner fileReader = new Scanner(System.in);
    System.out.println(fileReader.nextLine());
    fileReader.close();

    fileReader = new Scanner (new File("file.txt"));
    int i = 0;
    char[][] pic = new char[5][];
    while (fileReader.hasNextLine()){
        String line = fileReader.nextLine();
        pic[i] = line.toCharArray();
        System.out.println(line);
        i++;
    }
    fileReader .close();

output:

sadsadd sadsadd

sadasdasdasdsad sadasdasdsadsa sadasdasdsadsadsa dAS dASd

Process finished with exit code 0

Upvotes: 0

Arnaud
Arnaud

Reputation: 17534

Several things :

First, you are attempting to read a line for each index of your array (that is row*col times).

Second, you should only read a line by row.

You may replace your whole while loop with this :

    for (int u = 0; u < row && fileReader.hasNextLine(); u++) {

        String line = fileReader.nextLine();

        for (int i = 0; i < col; i++) {

            pic[u][i] = line.charAt(offset++);
        }

        offset = 0;
    }
    return pic;

Also , you probably want to reset the value of offset after each processed "row".

Upvotes: 1

Related Questions