0

I dont understand what is wrong with this code. I want to read txt file

11,10
2,20

into array[][] in java.

My code is

import java.util.Arrays;
class ArrayMatrix{
   public static void main (String[] args) {
   int rows = 2; 
   int cols = 2;
   FileInput in = new FileInput("test.txt");
   int[][] circle = new int[rows][cols]; 
   int i = 0; 
   int j = 0; 
   String [] line;
   for(i = 0; i<rows; i++) { 
       line = in.readString().split(",");
       for(j = 0; j<cols; j++) { 
           circle[i][j] = Integer.parseInt(line[j]);
           System.out.println(circle[i][j]);
       }
    }
}
}

The output is

11
10
2
20

Could you please help me understand why please?

I want the output

11 10
2 20
1
  • If you're happy with your answer, you should accept the best one (by clicking the tick next to an answer, turning it green) Commented Jan 6, 2011 at 0:39

3 Answers 3

2

You're output is like this since you're just using the System.out.println(circle[i][j]) command in the middle which only prints to a single line. Using the System.out.print command should help you print correctly. As show in the following altered code sample

import java.util.Arrays;
class ArrayMatrix{
   public static void main (String[] args) {
   int rows = 2; 
   int cols = 2;
   FileInput in = new FileInput("test.txt");
   int[][] circle = new int[rows][cols]; 
   int i = 0; 
   int j = 0; 
   String [] line;
   for(i = 0; i<rows; i++) { 
       line = in.readString().split(",");
       for(j = 0; j<cols; j++) { 
           circle[i][j] = Integer.parseInt(line[j]);
           System.out.print(circle[i][j] + " ");
       }
       System.out.println();
    }
}
}
Sign up to request clarification or add additional context in comments.

Comments

0

Why are you trying to split the string using comas, when you don't have comas separating values on each line?

line = in.readString().split(",");  //this is expecting coma separated values on each line

Also System.out.println() puts a new line at the end. So thats why they end on separate lines. Use System.out.print(circle[i][j]) instead.

Comments

0

When you use println(), each element is written on a new line. Try:

   for(j = 0; j<cols; j++) { 
       circle[i][j] = Integer.parseInt(line[j]);
       System.out.print(circle[i][j] + " ");
   }
   System.out.println();

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.