将Int值添加到二维数组

时间:2013-04-01 21:57:56

标签: java int multidimensional-array

我有这个代码,它打印一个4x4矩阵,所有值都为0.如何将代码添加到文件的输入值?

matdata1.txt文件显示为:

  

4 4

     

1 2 3 4

     

2 4 6 8

     

2 4 6 8

     

3 2 3 4

这是我的代码:

File f = new File( args[0]);
Scanner s = new Scanner(f);

int row = s.nextInt();
int col = s.nextInt();
int [] [] mat = new int [row] [col];



for(int i =0; i < row; i++)
{
    for( int j =0; j < col; j++)
    {
        System.out.print (mat[i][j] + " ");
    }
    System.out.println( );
}

2 个答案:

答案 0 :(得分:0)

已经有代码来输入文件中的值!

我在你发布的代码中添加了一些评论:

File f = new File( args[0]); // Get the input file
Scanner s = new Scanner(f);  // Open the file with a Scanner (a basic parsing tool)

int row = s.nextInt(); // Read the 1st number from the file as row count
int col = s.nextInt(); // Read the 2nd number from the file as column count
int [] [] mat = new int [row] [col]; // Use the row and column counts you read for the matrix dimensions

查看java.util.Scanner的文档以获取更多信息。

特别感兴趣的是示例代码中使用的nextInt()方法。

答案 1 :(得分:0)

BufferedReader in = new BufferedReader(new FileReader("filename.txt"));
StringTokenizer tk = new StringTokenizer(in.readLine());
int row = Integer.parseInt(tk.nextToken());
int col = Integer.parseInt(tk.nextToken());
int elem = 0;
for(int i=0;i<row;i++){
  tk = new StringTokenizer(in.readLine());
  for(int j=0;j<col;j++){
    elem = Integer.parseInt(tk.nextToken());
    arr[i][j] = elem;
  }
}