I need a functionalitty in my application, a method, to which you put as an argument link to an basic txt file, where are things stored in a simple format like this: "habitat=100000colony=50000..." I have an item class and an item object with String name and integer weight. In the file there is always first name which may be more than a one word, then "=" and then int as a weight. I have so far written this, but have a problem to make it work, so I i would be gratefull for some kind of a help.
This is the object which it is going to be stored into:
public class Item {
private String name;
private int weight;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
...
}
And then this is the method:
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;
}
When i run the simulation method with proper file, it says this:
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)
Could it not be working that when the file gets to the last item, to add i + 1 will try to parse as a int blank space and that gives an error ? Thanks once more.