从文件中读取二维数组

Nee*_*eel 4 java

我在文件'array.txt'中有一个2-D int数组.我试图在二维数组中读取文件中的所有元素.我在复制方面遇到问题.它显示复制后所有元素值为'0'而不是原始值.请帮我.我的代码是:

import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args) 
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }   

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

hel*_*922 9

while (input.next()!=null)

这将消耗扫描仪输入流中的内容.相反,尝试使用while (input.hasNextInt())

根据您希望代码的强大程度,您还应该在for循环中检查可以读取的内容.

Scanner input = new Scanner (new File("src/array.txt"));
// pre-read in the number of rows/columns
int rows = 0;
int columns = 0;
while(input.hasNextLine())
{
    ++rows;
    Scanner colReader = new Scanner(input.nextLine());
    while(colReader.hasNextInt())
    {
        ++columns;
    }
}
int[][] a = new int[rows][columns];

input.close();

// read in the data
input = new Scanner(new File("src/array.txt"));
for(int i = 0; i < rows; ++i)
{
    for(int j = 0; j < columns; ++j)
    {
        if(input.hasNextInt())
        {
            a[i][j] = input.nextInt();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用ArrayLists的替代方法(无需预读):

// read in the data
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
Scanner input = new Scanner(new File("src/array.txt"));
while(input.hasNextLine())
{
    Scanner colReader = new Scanner(input.nextLine());
    ArrayList col = new ArrayList();
    while(colReader.hasNextInt())
    {
        col.add(colReader.nextInt());
    }
    a.add(col);
}
Run Code Online (Sandbox Code Playgroud)

  • 你打开并阅读文件**两次**? (3认同)