Onelarian
Onelarian

Reputation: 1

File to 2D Array

I need to create a 2D array from a text file for later use in some operations.

This is my file separated by a space" ":

0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0

And this is the code that I have:

import java.io.*;

public class TxtToArray{
    public static void main(String args[]){
        double[][] array = new double[100][100];
        int x=0, y=0;

        try{
            BufferedReader in = new BufferedReader(new FileReader("E:\\Documents\\JavaPrograms\\TxtToArray\\src\\Array.txt"));
            String bar;

            while ((bar = in.readLine()) != null){
                String[] values = bar.split(" ");
                for (String str : values){
                    double str_double = Double.parseDouble(str);
                    array[x][y]=str_double;
                    y++;
                }
                x++;
            }

            in.close();

        }catch( IOException ioException ) {
            System.out.println("Something happened...");
        }
    }
}

Thanks! for the help

EDIT: I have corrected some errors in what came to be the explanation and code syntax. If there are more let me know.

Upvotes: 0

Views: 39

Answers (2)

fabian
fabian

Reputation: 82451

Your numers in the file are not only seperated by ,, but also by whitespaces. Double.parseDouble throws an exception, if this whitespace is included in the parameter. Therefore you need to use a regex that also matches these chars too, e.g. ,\s*. Also you need to set y back to 0 at the beginning of every iteration of the while loop:

while ((bar = in.readLine()) != null){
    String[] values = bar.split(",\\s*");
    y = 0;
    for (String str : values){
        double str_double = Double.parseDouble(str);
        array[x][y] = str_double;
        y++;
    }
    x++;
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

You never told us what the problem is, but one issue I see is that you are splitting each line of input on comma alone. This won't work because your input data also uses space as a delimeter. One option is to remove this whitespace before splitting by comma:

while ((bar = in.readLine()) != null) {
    String[] values = bar.replaceAll("\\s+", "")
                         .split(",");

    for (int y=0; y < values.length; ++y) {
        double str_double = Double.parseDouble(values[y]);
        array[x][y] = str_double;
    }

    x++;
}

You will notice that I used a for loop to iterate over the strings in each input. This is a nice option because it eliminates the need for you to manage the second index of your array.

Upvotes: 1

Related Questions