0

I'm having slight trouble converting a string which I am reading from a file into a multidimensional int array having found what I believe are suggestions here.

See this file here for string content.

Essentially I would like to replace the CR and LF so as to create a multi dimensional int array.

As per my code below where could I be going wrong?

public static void fileRead(String fileContent) {
    String[] items = fileContent.replaceAll("\\r", " ").replaceAll("\\n", " ").split(" ");

    int[] results = new int[items.length];

    for (int i = 0; i < items.length; i++) {
        try {
            results[i] = Integer.parseInt(items[i]);

            System.out.println(results[i]);
        } catch (NumberFormatException nfe) {};
    }
}

EDIT: I'm not encountering any errors. The above logic only creates an int array of size two i.e. results[0] = 5 and results[ 1] = 5

Thanks for any suggestions.

Community
  • 1
  • 1
ANM
  • 65
  • 1
  • 4
  • 11
  • You need to explain clearly what errors you're seeing. Also, why are you doing `replaceAll("\\r", " ")` twice? Did you mean for one of them to be `\\n`? – Nashenas Jun 01 '15 at 18:41
  • You may look at this link - http://stackoverflow.com/questions/22185683/read-txt-file-into-2d-array – Razib Jun 01 '15 at 18:44
  • @Nashenas: Thanks but i'm not encountering any errors. The above logic only creates an int array of size two i.e. results[0] = 5 and results[1] = 5 – ANM Jun 01 '15 at 18:44
  • The problem could be where you read the file. – user35443 Jun 01 '15 at 18:50
  • the challenge is the fact that my file content isn't a perfect string matrix i.e. the 1st 3 rows are only populated in y positions 0 1 and 2 and it is from the 4th row .. in saying this i used Razib's suggestion and i still came across the same issue .. using razibs suggestion it seems i need to determine the number of colmns by reading the last row – ANM Jun 01 '15 at 19:39
  • how do I go about determining the number of 2D colmns using the last string line read from my file – ANM Jun 01 '15 at 19:41

1 Answers1

1

Here's Java 8 solution:

private static final Pattern WHITESPACE = Pattern.compile("\\s+");

public static int[][] convert(BufferedReader reader) {
    return reader.lines()
            .map(line -> WHITESPACE.splitAsStream(line)
                    .mapToInt(Integer::parseInt).toArray())
            .toArray(int[][]::new);
}

Usage (of course you can read from file as well):

int[][] array = convert(new BufferedReader(new StringReader("1 2 3\n4 5 6\n7 8 9")));
System.out.println(Arrays.deepToString(array)); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334