本文介绍了从一个文本文件读取两个矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很长的

我有一个很奇怪的问题.我需要从文本文件中读取两个矩阵,将它们相乘,然后打印出结果.这很容易.问题在于包含矩阵的文件如下所示:

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):

  1. 读取第一列.按下空格或文件末尾后,FIRST矩阵中的行数就会增加.

  1. 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.

由于乘法运算要求矩阵一的列数与矩阵二的行数相同([3x6 * 6x4]有效,[3x6 * 5x4]无效),因此通过知道矩阵一的列数,我们可以找到矩阵2中的行数,反之亦然.

Since multiplication requires matrix one's column count to be the same as matrix two's row count ( [3x6 * 6x4] is valid, [3x6 * 5x4] 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.

我需要找到一个值.

因此从该文件矩阵中可以是

So from that file matrix one would be

1 2
3 4
5 6
7 8

两个是

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

所以我只需要一些有条件的操作即可,具体取决于左下角是int还是空白.我正在考虑将整个文件读入2D数组并从那里进行操作.

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:

我需要分别读取文件的每个字符(无论是int还是空格),因此我可以构建一个忠实的Array [] [].最好的方法是什么?我已经尝试过Scanner,StringTokenizer,FileInputStream,BufferedInputStream,Reader和FileReader,但是它们都不给我一个char的简单字符.

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.

第二,关于将矩阵从统一Array [] []分为两个较小的Array [] [] s的任何建议?

Secondly, any suggestions on splitting the matrices from the unified Array[][] into two smaller Array[][]s?

推荐答案

您应该能够使用FileInputStream逐字符读取文件.

You should be able to read in the file character by character with a FileInputStream.

请注意,read()方法在EOF处返回-1.否则,将返回的值强制转换为char.

Please note that the read() method returns -1 at EOF. Otherwise cast the returned value to a char.

这篇关于从一个文本文件读取两个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 14:47