繁体   English   中英

如何从文本文件中将整数读取到2D数组中?

[英]How to read integers from a text file into a 2D Array?

我在文本文件中有整数,所有整数之间都用空格隔开。

我知道如何读取文件,但不知道如何将整数放入数组中。 我知道我必须在某个地方使用parseInt

阵列为4x4。 整数是:

2 1 4 2  
9 7 5 3  
9 8 3 5  
1 0 0 0

我的代码:

arr = new int [4][4];
IODialog input = new IODialog();
String location = input.readLine("Enter the full path of the configuration text file: ");
Scanner scn = null;
try {
  scn = new Scanner(new BufferedReader(new FileReader(location)));
  int i, j = 0;
  String line = scn.nextLine(); 
  String[] numbers = line.split(" "); 
} finally {
  if (scn != null) {
    scn.close();
   }
}

这会有所帮助,

   int[][] a = new int[4][4];
   BufferedReader br = new BufferedReader(new FileReader("path/to/file"));

   for (int i = 0; i < 4; i++) {
        String[] st = br.readLine().trim().split(" ");
        for (int j = 0;j < 4; j++) {
            a[i][j] = Integer.parseInt(st[j]);
        }
   }

您走在正确的轨道上。

从扫描仪读取下一行后,只需填写阵列即可。

 int[][] arr = new int[4][4];
 String location = input.readLine("Enter the full path of the configuration text file: ");
 scn = new Scanner(new BufferedReader(new FileReader(location)));

 String line = scn.nextLine(); 
 String[] numbers = line.split(" "); 

 for(int i = 0; i < 4; i++)
     for(int j = 0; j < 4; j++)
         arr[i][j] = Integer.parseInt(numbers[j]); 

这将逐行读取您的输入,并在每行中插入整数以完成4x4数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM