I need to read in a list of adjacency matrices from a text file. I can get it to read in and write out when there is only one matrix in the file, but can't seem to get it to read through more than one. Once I tack another file onto the end of the other one, like this:
4
0 1 1 0
1 1 1 1
1 0 0 0
1 1 0 1
3
1 0 1
1 1 0
0 1 0
...I end up with this exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at GraphPath.buildMatrix(GraphPath.java:53)
at GraphPath.main(GraphPath.java:21)
Would you mind taking a look to see if you can help me figure out where I'm going wrong. Thanks.
chiotti
import java.io.*;
import java.util.*;
public class GraphPath
{
static BufferedReader input;
static PrintWriter output;
private static int numNodes;
private static int matrix[][];
public static boolean deBug = true;
public static boolean deBug2 = false;
public static void main(String [] args) throws IOException
{
GraphPath matrix = new GraphPath();
matrix.buildMatrix();
} //end main
public static void buildMatrix()throws IOException
{
input = new BufferedReader(new FileReader("Lab#2Input.txt"));;
output = new PrintWriter(new FileWriter("Lab#2Output.txt"));
String info;
numNodes = 0;
int rowIndex=0;
while ((info = input.readLine()) != null)
{
StringTokenizer t = new StringTokenizer(info);
if (t.countTokens() == 1)
{
numNodes = Integer.parseInt(info);
matrix = new int [numNodes][numNodes];
System.out.println ("numNodes: " + numNodes);
}
if (t.countTokens() >1)
{
int colIndex = 0;
while (t.hasMoreTokens() && t.countTokens() <= numNodes)
// while (t.hasMoreTokens())
{
String n = t.nextToken();
int m = n.charAt(0);
matrix[rowIndex][colIndex] = m;
colIndex = colIndex + 1;
}
rowIndex = rowIndex + 1;
}
}
output.println ("The adjacency matrix is: \n");
if (deBug){ System.out.print ("The adjacency matrix is: \n");}
for (int fm = 0; fm < numNodes; fm++)
{
for (int to = 0; to < numNodes; to++)
{
output.print ((char)matrix[fm][to] + "\t");
if (deBug){ System.out.print ((char)matrix[fm][to] + "\t");}
}
output.println ();
if (deBug){ System.out.println ();}
}
stringPrep();
output.println ();
if (deBug){ System.out.println ();}
//closes the PrintWriter and gives name of output file
if (output != null)
{
output.close();
System.out.println("Output file has been created: Lab#2Output.txt");
}
}