2016-05-14 149 views
0

即时尝试从文件创建矩阵,该文件是这样的: 其中我的第一行的大小为矩阵= 10 x 9 而在其他行中,我们有15个价值分布是偶然的。如何从文件读取数组

3 5 
4 5 6 
12 34 12 12 8 
34 23 
12 34 34 10 89 

随着信息大小我将定义我的matriz。我用这种方法阅读:

public static void read(){ 
    String line= ""; 
    int i = 0; 
    try { 
     while((line = bf.readLine()) != null){ 
      if (i == 0){ 
       //Call method that get the size and create my global matriz 
      }else{ 
       String[] list = line.split(" "); 
       //I need help here, for insert correctly in the array 
      } 
     i++; 
     } 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

我怎么能在矩阵中插入有序?我的矩阵应该是这样的:

4 5 6 12 34 
    12 12 8 34 23 
    12 34 34 10 89 

任何想法?

回答

1

这是做这件事:

String input = "3 5\n" + 
       "4 5 6\n" + 
       "12 34 12 12 8\n" + 
       "34 23\n" + 
       "12 34 34 10 89\n"; 
Scanner in = new Scanner(input); 
final int rows = in.nextInt(); 
final int cols = in.nextInt(); 
int[][] matrix = new int[rows][cols]; 
int row = 0, col = 0; 
for (int i = 0; i < rows * cols; i++) { 
    matrix[row][col] = in.nextInt(); 
    if (++col == cols) { 
     row++; 
     col = 0; 
    } 
} 
System.out.println(Arrays.deepToString(matrix)); 

输出:

[[4, 5, 6, 12, 34], [12, 12, 8, 34, 23], [12, 34, 34, 10, 89]] 

它不一定是做的最好的方式,但我想表现的col手动增量逻辑和row,其中rowcol翻转时递增。

使用answer by sebenalern,它会像这样工作:

int[][] matrix = new int[rows][cols]; 
for (int row = 0; row < rows; row++) 
    for (int col = 0; col < cols; col++) 
     matrix[row][col] = in.nextInt(); 

使用answer by Paul,它会像这样工作:

int[][] matrix = new int[rows][cols]; 
for (int i = 0; i < rows * cols; i++) 
    matrix[i/5][i % 5] = in.nextInt(); 

所有3个版本依靠Scanner简单地提供所有不管它们如何放在一起,它们都是按顺序排列的。

如果您不想使用Scanner(例如,因为速度较慢),并逐行读取输入,则线上的值第一版将更易于使用。否则第三个是最短的,第二个是最直接的。

0

只是一个提示 - 我会把作业留给你 - :
在这种情况下,维护一个已经读过的所有值的计数器是非常简单的,并且映射每个这些计数值以矩阵的值是这样的:

0 = (0 , 0) 
1 = (1 , 0) 
... 
5 = (0 , 1) 
6 = (1 , 1) 
... 

使用这样的事情:

int row = counter/rowLength; 
int col = counter % rowLength; 

你的情况:

matrix[counter/5][counter%5] = someValue;