【问题标题】:Read File Data stored in An Arraylist读取存储在 Arraylist 中的文件数据
【发布时间】:2015-12-29 22:47:54
【问题描述】:

我有一段代码可以读取板(第一项)的数据(高度、宽度、行、列)和放置在板上的块(其余项目):

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

public class readFile {
private Scanner scanner;
public void openFile() {

    try {
        scanner = new Scanner(new
File("filePath.txt"));
    }
    catch (Exception e)

    {
        System.out.println("File not found");
    }
 }
public void readTheFile(){
    while (scanner.hasNext()){

        int height = scanner.nextInt();
        int width = scanner.nextInt();
        int row = scanner.nextInt();
        int col = scanner.nextInt();

        System.out.printf("%s %s %s %s\n", height, width,row,col);
    }
}
public void closeFile(){
    scanner.close();
 }
}

这是输出:

5 4 0 0  //the dimensions of a board ; height, width, row, column
2 1 0 0 /*the rest are dimensions-heigh,width,row,column of blocks placed on 
2 2 0 1   the board*/
2 1 0 3 
2 1 2 0  
1 2 2 1 
1 1 3 1 
1 1 3 2 
1 1 4 0 
1 1 4 3

我希望将其存储在 Arraylist 中并返回。请帮助

This is what i want to end up with finally

【问题讨论】:

  • 创建一个代表每一行数据的 POJO,而不是打印结果,而是创建这个“行对象”的新实例并将其添加到 ArrayList

标签: java arrays arraylist input output


【解决方案1】:

首先创建一个 POJO(普通旧 Java 对象),它代表单独的数据行...

public class Row {

    private int height, width, row, col;

    public Row(int height, int width, int row, int col) {
        this.height = height;
        this.width = width;
        this.row = row;
        this.col = col;
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }

}

修改您的 readTheFile 方法以使用代表文件每一行的 Row 对象的实例填充 List 并返回此 List

public List<Row> readTheFile() {
    List<Row> rows = new ArrayList<>(25);
    while (scanner.hasNext()) {

        int height = scanner.nextInt();
        int width = scanner.nextInt();
        int row = scanner.nextInt();
        int col = scanner.nextInt();

        rows.add(new Row(height, width, row, col));
    }
    return rows;
}

查看Collections Trail了解更多详情

【讨论】:

  • 非常感谢@MadProgrammer;我如何继续将输出打印到控制台。我希望这个板和块以图形方式打印在板上。对不起,如果我听起来太天真了,我只是编程的初学者
  • 使用for-loop 遍历List,这将使您能够访问每个Row(或块)。您可能需要以某种有意义的方式对它们进行排序,具体取决于您想要做什么。看看The for Statement的初学者
猜你喜欢
  • 1970-01-01
  • 2017-04-25
  • 2015-02-24
  • 2013-02-23
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多