This is a long one.
I have a very odd problem. I need to read two matrices from a text file, multiply them together, and then print out the result. That’s all very easy. The problem is that the file containing the matrices looks like this:
1 2 1 2 3
3 4 4 5 6
5 6
7 8
How this crazy thing works is as follows (just for reference, you can skip this part):
-
Read down the first column. Once you hit whitespace OR the end of the file you have the number of rows in your FIRST matrix.
-
Count the number of integers per row, row-by-row. Once that count drops the you know how many rows your second matrix has. IF the first matrix was “shorter” than the file, then this step is unecessary, as the second will simply be the number of rows in the file.
-
Since multiplication requires matrix one’s column count to be the same as matrix two’s row count ( [3×6 * 6×4] is valid, [3×6 * 5×4] is not) then by knowing the number of columns in matrix one we can find the number of rows in matrix two, and vice-versa.
I need to find either value.
So from that file matrix one would be
1 2
3 4
5 6
7 8
and two is
1 2 3
4 5 6
So you’d think you could just count the rows in column one and the number of columns in the last row to find everything, but sometimes the file looks like this:
1 2 1 2 3
3 4 4 5 6
7 8
So I just need some conditional juggling depending on whether the bottom left corner is an int or whitespace. I’m thinking reading the whole file into a 2D Array and manipulating from there.
So here are my formal questions:
I need to read in every character of the file individually, whether it be int or whitespace, so I can build a faithful Array[][]. What is the best method of doing that? I have tried Scanner, StringTokenizer, FileInputStream, BufferedInputStream, Reader, and FileReader but none of them give me a simple char by char.
Secondly, any suggestions on splitting the matrices from the unified Array[][] into two smaller Array[][]s?
You should be able to read in the file character by character with a FileInputStream.
Please note that the
read()method returns -1 at EOF. Otherwise cast the returned value to a char.