开发者

Reading 2-D array from a file

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++)
                开发者_StackOverflow中文版System.out.println(a[i][j]);
        }

    }

}


while (input.next()!=null)

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

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

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


The problem is when u reach the end of the file it throughs an exception that no usch element exist.

 public static void main(String[] args) {
    // TODO Auto-generated method stub         
    try {
        Scanner input = new Scanner(new File("array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int[m][n];
        while (input.hasNextLine()) {
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                   try{//    System.out.println("number is ");
                    a[i][j] = input.nextInt();
                      System.out.println("number is "+ a[i][j]);
                    }
                   catch (java.util.NoSuchElementException e) {
                       // e.printStackTrace();
                    }
                }
            }         //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]);

                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I knew that making catch without processing the exception but it temporary works. Please be aware I put the file outside the source folder.


Well the problem may be that you've got that pair of nested loops to read the numbers stuck inside that while loop. Why would you want to re-read the array values after you've read them once? And note that if there's anything in the file after the last number, then you'll fill the array in with whatever .nextInt() returns after end-of-file has been reached!

edit — well .nextInt() should throw an exception I guess when input runs out, so that may not be the problem.


Start simple...

change:

for (int j=0;j<n;j++)
    a[i][j]= input.nextInt();

to:

for (int j=0;j<n;j++)
{
    int value;

    value = input.nextInt();
    a[i][j] = value;
    System.out.println("value[" + i + "][" + j + " = " + value);
}

And make sure that the values are read in.

Also, you should not call next without first calling (and checking) hasNext (or nextInt/hasNextInt).


You can try Using Guava ,

public class MatrixFile {
    private final int[][] matrix;

    public MatrixFile(String filepath) {
        // since we don't know how many rows there is going to be, we will
        // create a list to hold dynamic arrays instead
        List<int[]> dynamicMatrix = Lists.newArrayList();

        try {
            // use Guava to read file from resources folder
            String content = Resources.toString(
                Resources.getResource(filepath),
                Charsets.UTF_8
            );

            Arrays.stream(content.split("\n"))
                .forEach(line -> {
                    dynamicMatrix.add(
                        Arrays.stream(line.split(" "))
                            .mapToInt(Integer::parseInt)
                            .toArray()
                    );
                });
        } catch (IOException e) {
            // in case of error, always log error!
            System.err.println("MatrixFile has trouble reading file");
            e.printStackTrace();
        }

        matrix = dynamicMatrix.stream().toArray(int[][]::new);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜