Reputation: 81
So I've written this program that receives a text file, takes the data in that file and puts into a 2D char array to print to the screen in various ways. One of the files I have works perfectly, however, there is a problem when trying to print out the second file "diagonally". First, here is the first and simpler file that works just fine:
5 4
FILE
WITH
SOME
MORE
INFO
In both files, the first two integers indicate the number of rows and columns that will be created for the 2D char array, respectively. Next, here is a part of the code with this file "testfile.txt" and the results of the code:
public static void main(String[] args) throws IOException
{
char[][] charArray = readFile();
printArray(charArray);
printVerticalArray(charArray);
printHorizontalArray(charArray);
printDiagonalArray(charArray);
}
public static char[][] readFile() throws IOException
{
File myFile = new File("monalisa.txt");
Scanner inputFile = new Scanner(myFile);
int rows, columns;
rows = inputFile.nextInt();
columns = inputFile.nextInt();
String[] strArray = inputFile.nextLine().split(" ");
char[][] array = new char[rows][columns];
for(int i = 0; i < rows; i++)
{
array[i] = inputFile.nextLine().toCharArray();
}
return array;
}
.
.
.
public static void printDiagonalArray(char[][] cArray)
{
for(int i = 0; i < 1; i++)
{
for(int c = cArray[i].length - 1; c >= 0; c--)
{
for(int r = cArray[c].length; r >= 0; r--)
{
System.out.print(cArray[r][c]);
}
System.out.println();
}
System.out.println();
}
}
Results:
Original Text:
FILE
WITH
SOME
MORE
INFO
Transformations:
INFO
MORE
SOME
WITH
FILE
ELIF
HTIW
EMOS
EROM
OFNI
OEEHE
FRMTL
NOOII
IMSWF
So this is exactly how the program is supposed to work, however, whenever I try to put the second file "monalisa.txt" into the program, I get the array out of bounds exception and I cannot figure out why. Here is the original second text file (It's a Google Drive link because it would be too large to display here): https://drive.google.com/open?id=0BwujWiqVRKKsajlKV1NIWG1uQVU
And here is the result of program with this text file: https://drive.google.com/open?id=0BwujWiqVRKKsUnZYQTU4YmZDWUE
Line 78 in the code is:
for(int r = cArray[c].length; r >= 0; r--)
So would anyone happen to know why this is happening? And thank to anyone for reading through all of this!
Upvotes: 0
Views: 773
Reputation: 238
In line
for(int r = cArray[c].length; r >= 0; r--)
you are not setting initial value for r correctly. You should not check number of rows in current column, but number of rows in general since will be equal for every column. Change this line to
for(int r = cArray.length-1; r >= 0; r--)
Upvotes: 1