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.

6
  • 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? Commented Jun 1, 2015 at 18:41
  • You may look at this link - stackoverflow.com/questions/22185683/… Commented Jun 1, 2015 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 Commented Jun 1, 2015 at 18:44
  • The problem could be where you read the file. Commented Jun 1, 2015 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 Commented Jun 1, 2015 at 19:39

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.