Reading a 2-dimensional array from a file

I have a 2-D int array in the file 'array.txt'. I am trying to read all the elements in a file in a two dimensional array. I have problems copying. It shows all items having a value of "0" after copying instead of the 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]);
        }

    }

}
+3
source share
5 answers

while (input.next()!=null)

This will consume something from the scanner input stream. Try using insteadwhile (input.hasNextInt())

Depending on how reliable your code is, you should also check inside the for loop that something is readable.

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 &lt rows; ++i)
{
    for(int j = 0; j &lt columns; ++j)
    {
        if(input.hasNextInt())
        {
            a[i][j] = input.nextInt();
        }
    }
}

Alternative using ArrayLists (without prior reading):

// read in the data
ArrayList&ltArrayList&ltInteger&gt&gt a = new ArrayList&ltArrayList&ltInteger&gt&gt();
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);
}
+8
source

, , , , . , ? , -, , .nextInt() !

edit β€” .nextInt() , , , .

0

...

:

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

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

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

, .

, ( ) hasNext ( nextInt/hasNextInt).

0
source

The problem is when u reaches the end of the file, an exception is thrown through it that does not have the usch element.

 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 what to do the trick without handling the exception, but it temporarily works. Keep in mind that I put the file outside of the source folder.

0
source

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
source

Source: https://habr.com/ru/post/1787181/


All Articles