从文件中读取二维数组 [英] Reading 2-D array from a file

查看:104
本文介绍了从文件中读取二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me. My code is :

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]);
        }

    }

}


推荐答案

while(input.next()!= null)

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

This will consume something from the scanner input stream. Instead, try using while (input.hasNextInt())

取决于您希望代码的强大程度,你还应该在for循环内检查是否有东西可供阅读。

Depending on how robust you want your code to be, you should also check inside the for loop that something is available to be read.

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();
        }
    }
}

使用ArrayLists的替代方案(否)需要预读):

An alternative using ArrayLists (no pre-reading required):

// 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);
}

这篇关于从文件中读取二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆