【问题标题】:Reading data from a text file and building a table with arrays从文本文件中读取数据并用数组构建表
【发布时间】:2015-02-01 20:20:29
【问题描述】:

我有一个名为“animals.txt”的输入文件:

sheep 10.5 12.3 4
horse 8.4  11.2 7
cow   13.7 7.2  10
duck  23.2 2.5  23
pig   12.4 4.6  12

简单地说,我想知道如何将输入文件中的 4 列数据存储到 4 个单独的一维数组中。

输出应该是这样的......

[sheep, horse, cow, duck, pig]
[10.5, 8.4, 13.7, 23.2, 12.4]
[12.3, 11.2, 7.2, 2.5, 4.6]
[4, 7, 10, 23, 12]

到目前为止,我已经弄清楚如何将所有数据存储到一个大数组中,但我需要知道如何将其分解并将每一列存储到自己的数组中。

我的代码:

public static void main(String[] args) throws FileNotFoundException {

    String[] animal = new String[5];
    int index = 0;

    File file = new File("animals.txt");
    Scanner input = new Scanner(file);

    while (input.hasNextLine() && index < animal.length) {
        animal[index] = input.nextLine();
        index++;
    }

【问题讨论】:

    标签: java arrays io


    【解决方案1】:

    你可以使用一个数组来存储你需要的东西,比如:

    String[][] animal = new String[5][];
    

    然后,当您读取文件时,存储所有值的数组,如下所示:

    while (input.hasNextLine() && index < animal.length) {
        animal[index] = input.nextLine().split(" "); //split returns an array
        index++;
    }
    

    然后,当你想输出时,只需遍历数组数组即可:

    for (String[] a : animal)
    {
        for (int i = 0; i < a.length; i++)
            System.out.print(a[i] + ", ");
        System.out.println("");
    }
    

    【讨论】:

      【解决方案2】:

      下面是一种方法的代码 - 您可以将其剪切并粘贴到 Eclipse 等 IDE 中的 java 项目中并运行它,或者将其放入 file.java 并在命令行上编译和运行它。下一步将是完全通用地接受任何输入,包括具有可变列数且没有预定最大值的行,并且无需两次读取输入文件或将其存储为数组或其他对象的内存。

      import java.io.File;
      import java.io.FileNotFoundException;
      
      import java.util.ArrayList;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Scanner;
      
      public class BuildTableWithArrays {
      
          private static final String separator = "\\s+"; // regex for parsing lines
          private static final int rowWidth = 4;
      
          public static void main(String[] args) {
      
              Map<Integer, ArrayList<String>> columns = buildMapWithColumnArrayLists("animals.txt");
              printMap(columns);  // for demo
              // if you want actual arrays
              Map<Integer, String[]> colArrays = buildMapWithColumnArrays(columns);
      
          }
      
          public static Map<Integer, ArrayList<String>> buildMapWithColumnArrayLists(
              String fileName) {
      
              ArrayList<String> col0 = new ArrayList<String>();
              ArrayList<String> col1 = new ArrayList<String>();
              ArrayList<String> col2 = new ArrayList<String>();
              ArrayList<String> col3 = new ArrayList<String>();
      
              Map<Integer, ArrayList<String>> columns = new HashMap<Integer, ArrayList<String>>();
              columns.put(0, col0);
              columns.put(1, col1);
              columns.put(2, col2);
              columns.put(3, col3);
      
              File file = new File(fileName);
              try {
                  Scanner input = new Scanner(file);
                  while (input.hasNextLine()) {
                      String[] line = input.nextLine().trim().replaceAll(separator, " ")
                          .split(separator);
                      for (int i = 0; i < rowWidth; i++) {
                          if (line[i] == null) {
                              columns.get(Integer.valueOf(i)).add("null");
                          } else {
                              columns.get(Integer.valueOf(i)).add(line[i]);
                          }
                      }
                  }
                  input.close();
              } catch (FileNotFoundException x) {
                  System.out.println(x.getMessage());
              }
      
              return columns;
          }
      
          public static void printMap(Map<Integer, ArrayList<String>> columns) {
      
              for (int i = 0; i < rowWidth; i++) {
                  System.out.println("col" + i + " #elements = "
                      + columns.get(Integer.valueOf(i)).size());
                  for (String s : columns.get(Integer.valueOf(i))) {
                      System.out.print(s + " ");
                  }
                  System.out.println("\n");
              }
          }
      
          public static String[] convertArrayList2Array (ArrayList<String> arrayList) {
      
              String[] array = new String[arrayList.size()];
              array = arrayList.toArray(array);
              return array;
      
          }
      
          public static Map<Integer, String[]> buildMapWithColumnArrays(Map<Integer, ArrayList<String>> columns) {
      
              Map<Integer, String[]> cols = new HashMap<Integer, String[]>(); 
      
              for (Map.Entry<Integer, ArrayList<String>> entry : columns.entrySet()) {
                  Integer key = entry.getKey();
                  ArrayList<String> value = entry.getValue();
                  String[] val = convertArrayList2Array(value);
                  cols.put(key,val);
              }
      
              return cols;
      
          }
      
      }
      

      【讨论】:

        【解决方案3】:

        如果您的输入文件的结构得到保证,那么您可以使用扫描仪获取您需要的数据。首先用适当的类型声明您想要的 4 个数组。

        然后在你的while循环中使用:

          input.next()
        

        获取字符串

          input.nextInt()
        

        得到一个整数和

          input.nextDouble()
        

        获得双精度值。当然,您将这些值分配给适当的数组。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多