【问题标题】:read string array into an object array将字符串数组读入对象数组
【发布时间】:2020-11-05 22:44:10
【问题描述】:

我试图将一个文件读入一个数组,然后将该数组读入一个对象类,但它似乎只多次读取第一行。

String[] clothesFile = null;
Clothes[] clothes = new Clothes[2000];

br = new BufferedReader(new FileReader("clothes.csv"));

while ((line = br.readLine()) != null) {
    assets = line.split(",");

    name = clothes[0];
    style = clothes[1];
    colour = clothes[2];
    brand = clothes[3];
}

for (int ii = 0; ii < n; ii++) {
    clothes[ii] = new Clothes(name, style, colour, brand);
}

System.out.println("Clothes: ");
for (int ii = 0; ii < 10; ii++) {
    System.out.print(ii + 1 + ". ");
    System.out.print(clothes[ii]);
}

当我打印出衣服数组时,它只打印第一行 10 次,所以我假设它已经正确地创建了一个新对象。这与我混淆的循环有关吗?谢谢

【问题讨论】:

  • 您需要将衣服添加到您的阵列中,因为它正在穿过线条,而不是之后。您目前只是覆盖名称、样式、颜色和品牌变量,而不是在您遍历每一行之前存储它们,因此您只保留最后一个覆盖。
  • 我认为name = clothes[0]; 应该是name = assets[0];
  • @MNEMO 哎呀,我的真实代码是资产,它用于 16 个不同的变量,但我不想发布原始代码/它太长了哈哈一定错过了那个

标签: java arrays object


【解决方案1】:

您正在读取每一行,但仅将最后一行的数据传送到下一步,并在下一个 for 循环中一遍又一遍地重用它。

相反,每次阅读一行时创建并保存一个Clothes 对象,例如:

int ii = 0;
while ((line = br.readLine()) != null) {
    assets = line.split(",");

    name = clothes[0];
    style = clothes[1];
    colour = clothes[2];
    brand = clothes[3];
    clothes[ii++] = new Clothes(name, style, colour, brand);
}

【讨论】:

  • 你应该检查if(clothes.length == 4) { }以避免ArrayIndexOutOfBoundsException
  • @ArvindKumarAvinash 可以进行许多改进,但这是使 OP 移动的最小更改。
  • 我同意你的看法。不幸的是,即使是这样一件小事,我也有几次被否决了?。
【解决方案2】:

尝试以这种方式读取文件:

声明你的文件名:

public static final String FILE = "location/file.txt";

要读取文件,您有 3 种方法。 第一个调用其他的。

public ObjectList readObjects() throws FileNotFoundException {
        return readObjects(FILE);
    }

第二:

private ObjectList readObjects(String file) throws FileNotFoundException {
        return lerTarefas(new File(file));
    }

读取文件的第三个:

private ObjectList readObjects(File file) throws FileNotFoundException {
        try {
            Scanner in = new Scanner(file);
            ObjectList objectList = new Object();
            while (in.hasNext()) {
                String[] line = in.nextLine().trim().split(";");
                Object object = new Object(line[0].trim(), line[1].trim(), line[2].trim(), line[3].trim(),
                        Integer.parseInt(line[4].trim()), Double.parseDouble(line[5].trim()));
                if (!objectList.contains(object)) {
                    objectList.addObject(object);
                }
            }
            return objectList;
        } catch (FileNotFoundException fnfex) {
            throw new FileNotFoundException("File not found!");
        }
    }

试试这个。然后你只需编写一个打印对象信息的.toString()

【讨论】:

  • 欣赏它,但它比我拥有/需要的复杂得多
  • 没问题,我还是把它留在这里,因为它可以在将来帮助你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
相关资源
最近更新 更多