【问题标题】:How to properly initialize an ArrayList of an ArrayList of Integers read from input file [closed]如何正确初始化从输入文件中读取的整数 ArrayList 的 ArrayList [关闭]
【发布时间】:2018-10-18 04:24:58
【问题描述】:

我需要用这种格式解析一个输入文件。输入文件可以是任意大小,所以我决定使用列表而不是数组。解析数据后,我需要将其存储为数组。它代表 RGB 值。例如。这个 sn-p 是一个 2x2 像素的图像。

[251,255,128],[132,244,121]
[125,156,155],[157,200,090]

公共类 RGBFileReader {

public static void main(String[] args) {
    String filename;
    filename = args[0];
    new RGBFileReader().ReadRGBfile(filename);
} // end main method block

// declare the class constructor, pass filename parameter and initialize variables
public void ReadRGBfile (String filename) {
    int rowCount = 0;
    int columnCount = 0;
    int columnIndex = 0;

    //2D List = ArrayList of an ArrayList of Integers. ArrayList stores Objects not "ints"!
    ArrayList<ArrayList<Integer>> rgbArrayList = new ArrayList<ArrayList<Integer>>();

    try {
        //confirm current working directory for I/O files
        System.out.println("parsing input file at path: " + new File(".").getAbsoluteFile()+ filename);

        // pass the path to the file as a parameter 
        File file = new File("input/" + filename); 
        Scanner myScanner = new Scanner(file);

        // pattern match to sequence of comma delimited integers inside square brackets: [+/-int,+/-int,+/-int]    
        // -? = once or not at all, and minus sign handles negative numbers (although not strictly needed in this context)
        String patternToMatch = "\\[(-?\\d+),(-?\\d+),(-?\\d+)\\]";
        Pattern pattern = Pattern.compile(patternToMatch);

        // [\\d] = any digit, note need a second backslash to escape first backslash which is a java escape character
        // +     = 1 or more occurrences
        String innerpatternToMatch = "(\\d+)";
        Pattern innerpattern = Pattern.compile(innerpatternToMatch);

        while (myScanner.hasNextLine()) { // while loop to scan each line of input file
            ArrayList<Integer> singleRow = new ArrayList<Integer>();
            columnIndex = 0;
            System.out.println("rowCount: " + rowCount);
            String line = myScanner.nextLine();
            Matcher matcher = pattern.matcher(line);

            while (matcher.find()) { // outer while to parse groups of brackets

                System.out.println("columnCount: " + columnCount);
                String outerline = matcher.group();
                System.out.println("outerline: " + outerline);
                Matcher innermatcher = innerpattern.matcher(outerline);

                while (innermatcher.find()) { // inner while to parse triplets within brackets
                    String innerline = innermatcher.group();
                    System.out.println("innerline: " + innerline);
                    singleRow.add(Integer.valueOf(innermatcher.group())); //add triplets one at a time to inner List "oneRow"
                    System.out.println("singleRow = " + singleRow);
                    columnIndex++;
                } //end inner inner while
                columnCount = columnIndex;

            } // end outer while
            rgbArrayList.add(singleRow);  // add the oneRow of triplets, to the outer List "twodimArrayList"
            System.out.println("rgbArrayList dump using toString(): " + rgbArrayList.toString());
            System.out.println("\n");
            rowCount++;

        } // end scanner while loop
        myScanner.close();
        System.out.println("scanner is closed...");

    } // end Try block
    catch (FileNotFoundException e) {
        System.err.println("Could not open RGB input file: check it exists, is in the file path, or has correct format.");
    } //end catch block

    //sanity check for correct values of rowCount and columnCount
    System.out.println("\n");
    System.out.println("rowCount: " + rowCount);
    System.out.println("columnCount: " + columnCount);

    // Parsing of input file complete, now declare int[][] array
    int [][] rgbArray = new int [rowCount][columnCount];

    // check for expected values properly stored in ArrayList 
    System.out.println("\n"); 
    System.out.println("List<Integer> rgbArrayList values using iterator" );
    Iterator<ArrayList<Integer>> iterator = rgbArrayList.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }

    //Initialize the int [][] Array using values from the ArrayList
    System.out.println("\n");
    for (int row = 0; row < rowCount; row++) {
        for (int col = 0; col < columnCount; col++) {
            rgbArray[row][col] = rgbArrayList.get(row).get(col).intValue();
        } // end inner for loop
    } // end outer for loop

    System.out.println("rgbArray values"); 
    for (int i = 0; i < rowCount; i++) {
        System.out.println(Arrays.toString(rgbArray[i]));
    } // end inner loop

} // end method ReadRGBfile

} // 结束类

【问题讨论】:

  • 你为什么不简化这个使用java.awt.Color的列表?
  • 如果您可以突出显示实际问题所在的那几行代码,您将在此站点上更快地获得帮助。如果你不能这样做,那么也许你应该尝试使用调试器单步调试你的代码,看看它到底在哪里出错了。
  • 我不知道 java.awt.Color。我检查了它,它看起来很有用。
  • 如果具体问题不清楚,事后道歉。我试图在我的最新评论中更加具体。
  • 我已经编辑了这篇文章,希望能将消息搁置。如果不满意,欢迎反馈,使其符合论坛指南。谢谢。

标签: java regex arraylist multidimensional-array integer


【解决方案1】:

实际上并不存在 2D ArrayList 这样的东西。您正在创建一个列表列表,这意味着外部列表的每个元素都必须是新的ArrayList&lt;Integer&gt;,并且所有内部列表的大小不必彼此相同。尝试将 singleRow 声明移到 while 循环内并删除 singleRow.clear();

附带说明,添加到列表时不必使用索引。 twodimArrayList.add(singleRow); 将添加到列表的末尾。

【讨论】:

  • 按照建议,我移动了 ArrayList singleRow = new ArrayList();声明到 Scanner while 循环中,现在产生正确的结果(在我的编辑中更新了代码)。我不清楚为什么这解决了以前版本的代码中的问题,其中示例输入文件的最后一行被输入到整数数组中两次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多