开发者

file to array in java. what is wrong with this code?

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
开发者_如何学JAVA20

Could you please help me understand why please?

I want the output

11 10
2 20


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();
    }
}
}


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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜