读取部分字符串和部分整数并将其存储到Java中的对象

时间:2017-09-17 10:53:13

标签: java arrays arraylist

我需要在我的应用程序中使用一个函数,一个方法,你把它作为一个参数链接到一个基本的txt文件,其中的东西以这样的简单格式存储:“habitat = 100000colony = 50000 ......”我有一个item类和一个具有String名称和整数权重的item对象。在文件中总是有一个名字可能超过一个单词,然后是“=”然后是int作为权重。到目前为止我已经写了这篇文章,但是有一个问题要让它起作用,所以我会感激一些帮助。

这是将要存储的对象:

public class Item {
    private String name;
    private int weight;

    public Item(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }
    ...
}

然后这是方法:

    public ArrayList<Item> loadItems(File file) throws Exception {
        ArrayList<String[]> name = new ArrayList<>();

        Scanner scanner = new Scanner(file);
        ArrayList<Item> items = new ArrayList<>();

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            name.add(line.split("="));
        }

        for (int i = 0; i < name.size() + 1; i++) {
            items.add(new Item(Arrays.toString(name.get(i)), Integer.parseInt(Arrays.toString(name.get(i + 1)))));
        }

        return items;
    }

当我使用适当的文件运行模拟方法时,它会说:

Exception in thread "main" java.lang.NumberFormatException: For input string: "[building tools, 3000]"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.example.patrickpolacek.Simulation.loadItems(Simulation.java:26)
at com.example.patrickpolacek.Main.main(Main.java:11)

当文件到达最后一项时,添加i + 1会尝试解析为int空格并且出错吗?再次感谢。

2 个答案:

答案 0 :(得分:0)

以下是错误所在:

items.add(new Item(Arrays.toString(name.get(i)), Integer.parseInt(Arrays.toString(name.get(i + 1)))));

您正在使用Arrays.toString,它会返回"["habitat, 1000"]"之类的字符串。这不是你想要的,是吗?

你应该做的是从数组列表中获取字符串数组并获取数组的第一个和第二个元素,而不是数组列表。

items.add(
    new Item(
        name.get(i)[0], // first item of the array e.g. "colony"
        Integer.parseInt(name.get(i)[1]) // second item e.g. 10000
    )
);

另外,你的for循环有点偏。您应该循环到name.size(),而不是name.size() + 1

for (int i = 0; i < name.size(); i++) {

答案 1 :(得分:0)

只需将填充部分的项目更改为

for (int i = 0; i < name.size() ; i++) {
    String[] parsed = name.get(i);
    items.add(new Item(parsed[0],Integer.parseInt(parsed[1])));
}
相关问题