1

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

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

2 回答 2

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()您的示例代码中使用的方法。

于 2013-04-01T22:11:34.180 回答
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;
  }
}
于 2013-04-01T22:11:52.570 回答