7 Replies Latest reply: Nov 21, 2006 1:57 AM by 807607 RSS

    Reading from files into two-dimensional arrays

      Hi I'm pretty brand-spankin new when it comes to Java and the likes. I'm trying to read a file containing a square matrix of unknown size into a two-dimensional array, but I'm having troubles getting started.

      Is it better to use StringTokenizer or String.split?
      How about FileReader vs. FileInputStream?
      And how the heck do you make a string into a double? I've tried valueOf and parseDouble, but apparently I'm not writing it properly.

      Here's what I've done so far, obviously the line with the string tokenizer giving the matrix its next element is not compiling. Any help would be greatly appreciated...

      12 6 -6
      6 16 2
      -6 2 16

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

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

      public class matrixManipulations {
           private static int n = 0;     
           public double [][] matrix = new double [n][n];

           public static void main(String[] args) {
                Scanner scan = new Scanner(System.in);

                System.out.println("What is the name of your matrix file?");
                String fileName = scan.next();
                matrixManipulations m = new matrixManipulations();
           public void readFile(String fName){
                String name = fName;
                //String[] content = null;          
                BufferedReader bRead;

                     bRead = new BufferedReader(new FileReader(name));
                     int Integer = new Integer(bRead.readLine());
                     n = Integer;               
                     System.out.println("n = " + n);
                     double Double;
                     StringTokenizer stoke;
                     //String line;
                     //while (line != null){                    
                          for(int row = 0; row < n; row++){                         
                               for(int col = 0; col < n; col++){                              
                                    stoke = new StringTokenizer(bRead.readLine(), " " , false);                              
                                    Double = new Double(stoke.nextToken());
                                    matrix[row][col]= Double;
                                    System.out.print(" " + matrix[row][col] + " ");

                catch(IOException e){
                     System.out.println("This program can't read your file.");