How do I get individual characters from read in text file and store them into a 2D array?

S

Sam

Guest
So i have a text file that looks like this:

##oooooo
##oo#oo#
oo##o##o
oo##o##o
o#oo#oo#
oo##o##o
oo##o##o
o#oo#oo#


I want to insert it in the middle a 2D char array of size 10x10 full of '#'. So something like this.

##########
###oooooo#
###oo#oo##
#oo##o##o#
#oo##o##o#
#o#oo#oo##
#oo##o##o#
#oo##o##o#
#o#oo#oo##
##########


The code below first prints out a 2D array of pure '#'. I proceeded to read in the text file and grab ever individual character of each line and set them a char value at i and j position. And here is my code so far...

public static void readFromFile(String txtFile, char[][] hashArray)
{
// Displays basic 10x10 array of #
int counter = 0;
for (int i = 0; i < hashArray.length; i++)
{
for (int j = 0; j < hashArray.length; j++)
{
if (counter == 10)
{
System.out.println();
counter = 0;
}
hashArray[j] = '#';
System.out.print(hashArray[j]);
counter++;
}
}
System.out.println("\n");

counter = 0;
for (int i = 0; i < hashArray.length; i++)
{
for (int j = 0; j < hashArray.length; j++)
{
// I use a counter to skip to next line
if (counter == 10)
{
System.out.println();
counter = 0;
}
// Basically creates my # borders
if ((i == 0) || (i == 9) || (j == 0) || (j == 9))
{
hashArray[j] = '#';
System.out.print(hashArray[j]);
counter++;
}
else
{
// counter set at 2 compensates for the length of
// each line of read in text file.
counter = 2;
try
{
Scanner read = new Scanner(new File(txtFile));
while (read.hasNext())
{
String grid = read.nextLine();
char value = grid.charAt(i);
hashArray[j] = value;
System.out.print(hashArray[j]);
counter++;
}
}
catch (FileNotFoundException fnf)
{
System.out.println("File was not found.");
}
}
}
}
System.out.println();
}


When I run it, it gives me this error.

java.lang.StringIndexOutOfBoundsException: String index out of range: 8


I appreciate any and all help. Thanks.

Continue reading...
 
Top