在Java中从文件迭代到2d数组?
我试图读入一个文件并从文件内容生成一个2d数组 下面是我的实例变量和构造函数在Java中从文件迭代到2d数组?,java,arrays,parsing,Java,Arrays,Parsing,我试图读入一个文件并从文件内容生成一个2d数组 下面是我的实例变量和构造函数 私有int[][]矩阵; 私有布尔平方; //建设者 公共MagicSquare(字符串文件名) { 试一试{ 扫描仪扫描=新扫描仪(新文件(文件名)); int-dimensions=Integer.parseInt(scan.nextLine()); int行=0; int col=0; this.matrix=新整数[维度][维度]; while(scan.hasNextLine()) { String lin
私有int[][]矩阵;
私有布尔平方;
//建设者
公共MagicSquare(字符串文件名)
{
试一试{
扫描仪扫描=新扫描仪(新文件(文件名));
int-dimensions=Integer.parseInt(scan.nextLine());
int行=0;
int col=0;
this.matrix=新整数[维度][维度];
while(scan.hasNextLine())
{
String line=scan.nextLine();
扫描仪行扫描=新扫描仪(行);
while(行<尺寸)
{
this.matrix[row][col++]=lineScan.nextInt();
行++;
}
lineScan.close();
}
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
当我试着在测试软件中运行它时,我得到了以下结果
Expected :
4 9 2
3 5 7
8 1 6
Returned :
4 0 0
0 9 0
0 0 2
这让我相信我在迭代中做了一些错误的事情。关于我应该在哪里查找的任何提示或提示?您可以有效地同时增加行和列,每读一个数字就增加一次:
while (row < dimensions)
{
this.matrix[row][col++] = lineScan.nextInt();
row++;
}
请注意,循环更清晰地写成for
循环:
for (int col = 0; col < dimensions; ++col)
{
this.matrix[row][col] = lineScan.nextInt();
}
row++;
行和列实际上同时递增。我应该在while循环之外递增行吗?因为这最终导致整个事情比我现在所拥有的更不正常,我想知道我是否应该在这里探索一个for循环,而不是一个while。这可能是沿着正确的轨道进行的,但会给我带来一大堆索引越界错误
for (int col = 0; col < dimensions; ++col)
{
this.matrix[row][col] = lineScan.nextInt();
}
row++;
for (int row = 0; scan.hasNextLine(); ++row)
// instead of while (scan.hasNextLine()) and incrementing row separately.