【问题标题】:Read each line from a file into its own different 2D array将文件中的每一行读入其自己不同的二维数组
【发布时间】:2020-04-20 18:10:15
【问题描述】:

我想从 Java 中读取文件。复杂之处在于将其管理到自己的二维数组中。 文件如下:

#  1  1    1  2    1  3    1  4    1  5    2  3      8   8      9   7    18  17 
*  2  4    2  5    2  6    2  7    2  8    18  18    10  11     16  18 
HRow 5 5 20 3
VRow 6 6 10 4

空格是对之间的分隔符。对内有 2 个空格,对之间有 3 个空格。

输出应该是:

private static final int[][] HASH_LOCATIONS = {{1,1},{1,2},{1,3},{1,4},{1,5},{2, 3}, {8, 8}, {9, 7}, {17, 18}};
private static final int[][] AST_LOCATIONS = {{2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, {18, 18}, {10, 11}, {16, 18}};
private static final int [][] H_ROW = {{5,5,20,3}};
private static final int [][] V_ROW = {{6,6,10,4}};

我尝试了以下方法:

       try {
            FileInputStream fileIn = new FileInputStream(fileName);
            Scanner scanner = new Scanner(fileIn);
        while (scanner.hasNext()){
            String itemType = scanner.next();
            if (itemType.equals("#")) {
                ArrayList<Integer> hashLocations = new ArrayList<>();
                while(scanner.hasNextInt()){
                    hashLocations.add(scanner.nextInt());
                }
            } else if (itemType.equals("*")) {
                ArrayList<Integer> astLocations = new ArrayList<>();
                while(scanner.hasNextInt()){
                    astLocations.add(scanner.nextInt());
                }
            } else if (itemType.equals("HRow")) {
                ArrayList<Integer> hLocations = new ArrayList<>();
                while(scanner.hasNextInt()){
                    hLocations.add(scanner.nextInt());
                }
            } else if (itemType.equals("VRow")) {
                ArrayList<Integer> vLocations = new ArrayList<>();
                while(scanner.hasNextInt()){
                    vLocations.add(scanner.nextInt());
                }
            }
        }
            return true;
        } catch (FileNotFoundException ex) {
            return false;
        }

我不确定如何管理。任何帮助,将不胜感激。

【问题讨论】:

    标签: java file multidimensional-array java.util.scanner


    【解决方案1】:

    我会逐行而不是逐字符读取。对于每一行,如果您知道配对的数量(例如:预期的数字),我会计算它们以确保它们没问题。

    如果文件在对的前面有这些定义(例如:#、* 等),那么我将确保将它们放入正确的“桶”中。我将为此使用地图,因此它可以很容易地添加新值。但是,如果您只想限制这些并炸毁其他任何东西,那么这也可以实现。

    另外请注意,您在输入文件中的某些空格可能是错误的,除非您的定义是错误的,所以请检查一下。

    请参阅下面的一些示例以帮助您入门。这是基于附加的示例输入(除了遵循间距规则外,这与您的输入无关)

    public static void main(String[] args) {
        final int EMPTY_COUNT_BETWEEN_TUPLES = 2; // after split
        List<String> allowedRowTypes = Arrays.asList("*", "#", "HRow", "VRow");
        Map<String, List<List<Integer>>> buckets = new HashMap<>();
    
    
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader("C:\\Users\\e048222\\Playground\\stackoverflowPlay\\src\\com\\company\\input.txt"));
            String line = reader.readLine();
            while(line != null) {
                System.out.println(line);
                String[] tokens = line.split(" ");
    
                if(tokens.length == 0) {
                    throw new IllegalArgumentException("Invalid line");
                }
                String rowType = tokens[0];
                if(!allowedRowTypes.contains(rowType)) {
                    throw new IllegalArgumentException("Invalid line type");
                }
                List<Integer> tuple = null;
                int countEmpty = 0;
                List<List<Integer>> bucketValues = buckets.get(rowType);
                for(int tokenCount=1; tokenCount<tokens.length; tokenCount++) {
                    String value = tokens[tokenCount];
                    if(value.isEmpty()) {
                        countEmpty++;
                    } else {
                        if(countEmpty == EMPTY_COUNT_BETWEEN_TUPLES) {
                            bucketValues = addToBucket(tuple, bucketValues);
                            tuple = null;
                        }
    
                        if(tuple==null) {
                            tuple = new ArrayList<>();
                        }
    
                        tuple.add(Integer.parseInt(value));
                        countEmpty = 0;
                    }
                }
                bucketValues = addToBucket(tuple, bucketValues);
                buckets.put(rowType, bucketValues);
                System.out.println(bucketValues);
    
                line = reader.readLine();
            }
    
    
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    
        System.out.println(buckets);
    }
    
    private static List<List<Integer>> addToBucket(List<Integer> tuple, List<List<Integer>> bucketValues) {
        if (bucketValues == null) {
            bucketValues = new ArrayList<>();
        }
        bucketValues.add(tuple);
        return bucketValues;
    }
    

    更新的输入文件:

    # 1  1   1  2   1  3   1  4   1  5   2  3   8  8   9  7   18  17
    * 2  4   2  5   2  6   2  7   2  8   18  18   10  11   16  18
    HRow 5  5  20  3
    VRow 6  6  10  4
    

    输出:

    # 1  1   1  2   1  3   1  4   1  5   2  3   8  8   9  7   18  17
    [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [8, 8], [9, 7], [18, 17]]
    * 2  4   2  5   2  6   2  7   2  8   18  18   10  11   16  18
    [[2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [18, 18], [10, 11], [16, 18]]
    HRow 5  5  20  3
    [[5, 5, 20, 3]]
    VRow 6  6  10  4
    [[6, 6, 10, 4]]
    {#=[[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [8, 8], [9, 7], [18, 17]], HRow=[[5, 5, 20, 3]], *=[[2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [18, 18], [10, 11], [16, 18]], VRow=[[6, 6, 10, 4]]}
    

    不是最简洁的代码,而是让您的创意源源不断的东西。这对于输入文件的几乎任何结构更改都将失败,但允许进行很多改进。

    【讨论】:

    • 谢谢。这肯定有帮助。会尽快更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 2014-09-13
    相关资源
    最近更新 更多