CheaterBeef
CheaterBeef

Reputation: 1

How to read a file with scanner, then put into a 2D array of characters

I have a text file that basically has a picture with a bunch of characters.

I'm using scanner.nextLine and saving it to a string, then using charAt(index) of that string to get the individual character at each spot and saving it to matrix[I][j]. When I try to print out the picture with a nested for loop, it looks nothing like the text file looks.

String string;
Scanner pic = new Scanner(new File("/Users/yoyoma/eclipse-workspace/Picture/resources/pics/" + filename));
int row = pic.nextInt();
int col = pic.nextInt();
char[][] picture = new char[row][col];
for(int i = 0; i < row; i++) {
    if(pic.hasNextLine()) {
        string = pic.nextLine();
        for(int j = 0; j < col; j++) {
            for(int a = 0; a < string.length(); a++) {
                picture[i][j] = string.charAt(a);
            }
        }
     }
}
for (int z = 0; z < row; z++) {
    for (int x = 0; x < col; x++) {
        System.out.print(pic[z][x]);
        }
        System.out.println();
}

I expected the picture to look the way it does in the text file, instead I get a big 'ol jumble of characters in the wrong order and some even missing.

//This is what the text file looks like:

10 10
## #######
#         
#   #     
#   ######
#     #  #
#G    #  #
#     #  #
# L   #  #
#        #
######## #

//Here is my output:


##########


##########
##########
##########
##########
##########
##########

Upvotes: 0

Views: 38

Answers (1)

Marc G. Smith
Marc G. Smith

Reputation: 886

The issue you have is with your reader. Specifically

        for(int j = 0; j < col; j++) {
            for(int a = 0; a < string.length(); a++) {
                picture[i][j] = string.charAt(a);
            }
        }

You're basically reading the line 10 times and setting every column to the last character of the line by the end of each loop of j.

You need to modify it to:

        for(int j = 0; j < col; j++) {
                picture[i][j] = string.charAt(j);
        }

Upvotes: 1

Related Questions