1

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]);
}
3
  • are you sure your text file contains tab-separated fields? If not, the split() command won't work Commented Jan 2, 2011 at 15:26
  • also what is your FileInput class? Do you have any import statements? Commented Jan 2, 2011 at 15:28
  • i am not sure what to say, sorry. i really dont know much about computer sciences. i just want to create 4x4 matrix array and the data is stored in txt file (in the above format) saved in the same directory. Commented Jan 2, 2011 at 15:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. can you please help me understand in.readString method? why string? should that not be in.readInteger()? the file above doesnt have strings. strings are like letters, arent they?
in.readString is used to read an entire line as a string of characters e.g. "0 2 100 1". You then call split to split this string (on tab) into an array of smaller strings {"0", "2", "100", "1"}. Finally, Integer.parseInt is used to convert strings to ints.

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.