Read a 2d integer array from file and display in console

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 4614 Views - Last Post: 06 June 2011 - 06:02 AM Rate Topic: -----

#1 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Read a 2d integer array from file and display in console

Posted 03 June 2011 - 04:54 PM

I am trying to write a program that will read a file that contains a 2d integer array and then display that array in the console.
The input file would contain an arrary like this:

1 4 6 5
2 7 5 3

The code that I have written compiles without any errors, but does not execute properly.
I have determined that there is something wrong with the while loop that I have used to determine the size of the array in the file, but I cannot figure out what it is. If I add a print statement to display the value of the variable row the output is 5, which clearly is not correct. If I try to add a print statement to display the value of the variable col it seems like an infinite loop occurs.


import java.io.*;
import java.util.*;
        
public class Read_2d_Array_Main {
    
    public static void main(String[] args) throws FileNotFoundException{
        int[][] a;
        int row = 0, col = 0;
        Scanner inFile = null;
        
        inFile = new Scanner (new File("matrix1.txt"));
        // determine the number of rows/columns

        while(inFile.hasNextLine()) {
          row++;
          Scanner matCol = new Scanner(inFile.nextLine());
          while(matCol.hasNextInt())
          {
           col++;
          }
        }
        a = new int[row][col]; 
        inFile.close();
        a = readMatrix("matrix1.txt", row, col);
        printMatrix(a, row, col);
    }
    
    
    public static int[][] readMatrix(String fileName,int row, int col) throws FileNotFoundException {
        int[][] matrix = new int[row][col];
        
        Scanner inFile = new Scanner(new File(fileName));
        for(int r = 0; r < row; r++) {
          for(int c = 0; c < col; c++) {
            if(inFile.hasNextInt()) {
              matrix[r][c] = inFile.nextInt();
            }
          }
          
        }
        inFile.close();
        
        return matrix;
    }
    public static void printMatrix(int[][] matrix, int row, int col) {
      for (int r = 0; r < row; r++){
        for (int c = 0; c < col; c++)
          System.out.printf("%5d", matrix[r][c]);
        System.out.println();
      }
    } 
}


Is This A Good Question/Topic? 0
  • +

Replies To: Read a 2d integer array from file and display in console

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,372
  • Joined: 27-December 08

Re: Read a 2d integer array from file and display in console

Posted 03 June 2011 - 04:58 PM

Keep in mind that arrays are static. You cannot resize them. I would suggest using an ArrayList<ArrayList<Integer>> so as not to worry about the dimensions of the matrix in the File.

http://download.orac.../ArrayList.html
Was This Post Helpful? 0
  • +
  • -

#3 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Re: Read a 2d integer array from file and display in console

Posted 03 June 2011 - 05:35 PM

View Postmacosxnerd101, on 03 June 2011 - 04:58 PM, said:

Keep in mind that arrays are static. You cannot resize them. I would suggest using an ArrayList<ArrayList<Integer>> so as not to worry about the dimensions of the matrix in the File.

http://download.orac.../ArrayList.html

I need to write a method to read the array, so ArrayList<ArrayList<Integer>> isn't an option.
Any idea why the code I wrote to determine the number of rows and columns in the array doesn't work?
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 07:25 PM


while(matCol.hasNextInt())
          {
           col++;
          }


while input has next int you increment col... but you actually never read that int
this is an infinite loop
there will always be another next int if you never read it
Was This Post Helpful? 1
  • +
  • -

#5 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 07:43 PM

View Postpbl, on 04 June 2011 - 07:25 PM, said:


while(matCol.hasNextInt())
          {
           col++;
          }


while input has next int you increment col... but you actually never read that int
this is an infinite loop
there will always be another next int if you never read it


OK the program runs, but it showing that the value of row is 9 and col is 3. Also it prints a matrix of those dimensions but all of the values are zero, so I'm guessing there's also something wrong with the method I wrote to read the 2d array. I'm using a Mac and the file that I am reading was created using Text Edit. Is there any chance that this is what is causing the incorrect values for row and col?
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 07:49 PM

No

How do you determine the number of rows in your array ? You read your file twice ?
Was This Post Helpful? 0
  • +
  • -

#7 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 07:56 PM

View Postpbl, on 04 June 2011 - 07:49 PM, said:

No

How do you determine the number of rows in your array ? You read your file twice ?

while(inFile.hasNextLine()) {
15	          row++;
16	          Scanner matCol = new Scanner(inFile.nextLine());
17	          while(matCol.hasNextInt())
18	          {
19	           col++;
20	          }
21	        }


This was what I came up with. Clearly it's not working, though.
Was This Post Helpful? 0
  • +
  • -

#8 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 08:02 PM

Sorry posted the old code. Should be this:
        while(inFile.hasNextLine()) {
          row++;
          matCol = new Scanner(inFile.nextLine());
          while (matCol.hasNextInt()){
            col++;
            matCol.next();
          }
         }

Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 08:09 PM

NO, nextInt() reads the next int on the same line or not
If you are uring arrays, you will have to do it in 2 pass:
the first one to read the number of lines to determine the number of row, so you can create and array with the good number of row. And then a secondd pass to read the actual numbers. Something like that (without the try/catch):

Scanner in = new Scanner("Matrix.txt");
int nbRow = 0;
// read the file to get number of lines
while(in.hasNextLine()) {
  ++nbRow;
  in.nextLine();
}
in.close();
// now build an int array based on the number of row
int[][] number = new int[nbRow][];
in = new Scanner("Matrix.txt");
for(int i = 0; i < nbRow; ++i) {
   // read each line
   String line = in.nextLine();
   // split it on " "
   String[] token = line.split(" ");
   // add the columns to each row
   number[i] = new int[token.length];
   // translate to int each token
   for(int j = 0; j < token.length; ++j)
      number[i][j] = Integer.parseInt(token[j]);
}
in.close();


Was This Post Helpful? 0
  • +
  • -

#10 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 08:36 PM

Ok it's still saying that the number of columns is 9.
Was This Post Helpful? 0
  • +
  • -

#11 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Re: Read a 2d integer array from file and display in console

Posted 04 June 2011 - 09:37 PM

Also, tested the code that you wrote and got this error message:

java.lang.NumberFormatException: For input string: "Matrix.txt"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at MichaelLevero_Lab2_Main.main(MichaelLevero_Lab2_Main.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
Was This Post Helpful? 0
  • +
  • -

#12 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,372
  • Joined: 27-December 08

Re: Read a 2d integer array from file and display in console

Posted 05 June 2011 - 12:12 PM

pbl created a Scanner around Matrix.txt. You don't have to enter it into the console.
Was This Post Helpful? 1
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Read a 2d integer array from file and display in console

Posted 05 June 2011 - 05:19 PM

View Postmlevero, on 05 June 2011 - 12:37 AM, said:

Also, tested the code that you wrote and got this error message:

java.lang.NumberFormatException: For input string: "Matrix.txt"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at MichaelLevero_Lab2_Main.main(MichaelLevero_Lab2_Main.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)

Post your revised code
No reason why it shouldn't work
You missed something
Was This Post Helpful? 0
  • +
  • -

#14 mlevero  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 03-June 11

Re: Read a 2d integer array from file and display in console

Posted 05 June 2011 - 05:33 PM

import java.io.*;
import java.util.*;
        
public class Read_2d_Array {
    
    public static void main(String[] args) throws FileNotFoundException{
      
      Scanner in = new Scanner("Matrix1.txt");
      int nbRow = 0;
      // read the file to get number of lines
      while(in.hasNextLine()) {
        ++nbRow;
        in.nextLine();
      }
      in.close();
      // now build an int array based on the number of row
      int[][] number = new int[nbRow][];
      in = new Scanner("Matrix1.txt");
      for(int i = 0; i < nbRow; ++i) {
        // read each line
        String line = in.nextLine();
        // split it on " "
        String[] token = line.split(" ");
        // add the columns to each row
        number[i] = new int[token.length];
        // translate to int each token
        for(int j = 0; j < token.length; ++j)
          number[i][j] = Integer.parseInt(token[j]);
      }
      in.close();
    }
}

Was This Post Helpful? 0
  • +
  • -

#15 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Read a 2d integer array from file and display in console

Posted 05 June 2011 - 05:40 PM

So obviously you have something else than int in your file

       // translate to int each token
        for(int j = 0; j < token.length; ++j) {
          System.out.println("Trying to translate to int ", token[j]);
          number[i][j] = Integer.parseInt(token[j]);
        }


Should should you which String yo try to convert to int and is not an int
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2