user560084
user560084

Reputation: 57

Text file to array in java

I want to read a text file

0 2 100 1

2 0 7 100

100 7 0 11

1 100 11 0

into array[][] in java. I am new to computer science and don't know much about java. I am trying to make changes to the following code (which was written by someone else) to do the task.

int rows = 4; int cols = 4;

FileInput in = new FileInput(args[0]);

int[][] val = new int[rows][cols]; 

String[] line;

for(int i=0; i < rows; i++) 
{
    line = in.readString().split("\t");
}

for(int j=0; j < cols; j++) 
{
    val[i][j] = Integer.parseInt(line[j]);
}

Upvotes: 1

Views: 1591

Answers (1)

dogbane
dogbane

Reputation: 274562

Your for loops need to be nested like this:

for(int i=0; i < rows; i++) 
{
    line = in.readString().split("\t");
    for(int j=0; j < cols; j++) 
    {
        val[i][j] = Integer.parseInt(line[j]);
    }
}

Also check that your file is correctly formatted i.e. it has tabs to separate the numbers on each line.

Upvotes: 1

Related Questions