【问题标题】:How to read integers from a text file into a 2D Array?如何将文本文件中的整数读入二维数组?
【发布时间】:2015-03-24 15:24:58
【问题描述】:

我在文本文件中有整数,全部用空格分隔。

我知道如何读取文件,但我不知道如何将整数放入数组中。我知道我必须在某处使用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();
   }
}

【问题讨论】:

  • 即使是年轻的巫师也必须展示一些初步的工作——你已经走了多远?

标签: java arrays parseint


【解决方案1】:

这会很有帮助,

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

【讨论】:

    【解决方案2】:

    你在正确的轨道上。

    在您从扫描仪读取下一行后立即填写您的数组。

     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 数组。

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2013-03-11
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      相关资源
      最近更新 更多