views:

55

answers:

3

I want to read in a grid of numbers (n*n) from a file and copy them into a multidimensional array, one int at a time. I have the code to read in the file and print it out, but dont know how to take each int. I think i need to splitstring method and a blank delimiter "" in order to take every charcter, but after that im not sure. I would also like to change blank characters to 0, but that can wait!

This is what i have got so far, although it doesnt work.

        while (count <81  && (s = br.readLine()) != null)
        {
        count++;

        String[] splitStr = s.split("");
        String first = splitStr[number];
        System.out.println(s);
        number++;

        }
    fr.close();
    } 

A sample file is like this(the spaces are needed):

26     84
 897 426 
  4   7  
   492   
4       5
   158   
  6   5  
 325 169 
95     31

Basically i know how to read in the file and print it out, but dont know how to take the data from the reader and put it in a multidimensional array.

I have just tried this, but it says 'cannot covernt from String[] to String'

        while (count <81  && (s = br.readLine()) != null)
    {       
    for (int i = 0; i<9; i++){
        for (int j = 0; j<9; j++)
            grid[i][j] = s.split("");

    }
A: 

EDIT: You just updated your post to include a sample input file, so the following won't work as-is for your case. However, the principle is the same -- tokenize the line you read based on whatever delimiter you want (spaces in your case) then add each token to the columns of a row.

You didn't include a sample input file, so I'll make a few basic assumptions.

Assuming that the first line of your input file is "n", and the remainder is the n x n integers you want to read, you need to do something like the following:

public static int[][] parseInput(final String fileName) throws Exception {
 BufferedReader reader = new BufferedReader(new FileReader(fileName));

 int n = Integer.parseInt(reader.readLine());
 int[][] result = new int[n][n];

 String line;
 int i = 0;
 while ((line = reader.readLine()) != null) {
  String[] tokens = line.split("\\s");

  for (int j = 0; j < n; j++) {
   result[i][j] = Integer.parseInt(tokens[j]);
  }

  i++;
 }

 return result;
}

In this case, an example input file would be:

3
1 2 3
4 5 6
7 8 9

which would result in a 3 x 3 array with:

row 1 = { 1, 2, 3 }
row 2 = { 4, 5, 6 }
row 3 = { 7, 8, 9 }

If your input file doesn't have "n" as the first line, then you can just wait to initialize your final array until you've counted the tokens on the first line.

Segphault
A: 
private static int[][] readMatrix(BufferedReader br) throws IOException {
    List<int[]> rows = new ArrayList<int[]>();
    for (String s = br.readLine(); s != null; s = br.readLine()) {
        String items[] = s.split(" ");
        int[] row = new int[items.length];
        for (int i = 0; i < items.length; ++i) {
            row[i] = Integer.parseInt(items[i]);
        }
        rows.add(row);
    }
    return rows.toArray(new int[rows.size()][]);
}
Maurice Perry
Can you do that last line? Do the generics work like that?
jjnguy
Yep............
Maurice Perry
A: 

Based on your file this is how I would do it:

Lint<int[]> ret = new ArrayList<int[]>();

Scanner fIn = new Scanner(new File("pathToFile"));
while (fIn.hasNextLine()) {
    // read a line, and turn it into the characters
    String[] oneLine = fIn.nextLine().split("");
    int[] intLine = new int[oneLine.length()];
    // we turn the characters into ints
    for(int i =0; i < intLine.length; i++){
        if (oneLine[i].trim().equals(""))
            intLine[i] = 0;
        else
            intLine[i] = Integer.parseInt(oneLine[i].trim());
    }
    // and then add the int[] to our output
    ret.add(intLine):
}

At the end of this code, you will have a list of int[] which can be easily turned into an int[][].

jjnguy
Thanks. For the lines int[] intLine = new int[oneLine.length()]; for(int i =0; i < intLine.length(); i++){ it says 'cannot invoke length() on the array type String[]' how do i resolve this issue?
oops, remove the parentheses. It should be `intLine.length`
jjnguy
Ah, i previously did that and got the error 'Exception in thread "main" java.lang.NumberFormatException: For input string: " "' Sorry for being a pain
@user Ok, you should probably add a call to `trim()` when you are looking at each character. See my updated answer, or - `if(oneLine[i].trim().equals(""))` `intLine[i] = 0;` `else` `intLine[i] = Integer.parseInt(oneLine[i].trim());`
jjnguy