gpt4 book ai didi

java - Java新手。如何使用文本文件将项目添加到特定存储库

转载 作者:行者123 更新时间:2023-11-30 11:06:36 24 4
gpt4 key购买 nike

我的主课

int n, p;
String d;
manager m = new manager();

Scanner f = new Scanner(i.class.getResourceAsStream("product.txt"));
while (f.hasNextLine()) {
String[] s = f.nextLine().split(",");
n = Integer.parseInt(tokens[0]);
d = s[1];
p = Integer.parseInt(s[2]);

Item item = new Item(itemNo, description, price);
m.addItems(item);

if (s[3].contains("1")) {
m.addRep(1, item);
}
if (s[3].contains("2")) {
m.addRep(2, item);
}
if (s[3].contains("3")) {
m.addRep(3, item);
}

}
}

我的文本文件中的示例:

34,表,1200,12

14,沙发,2950,123

s[3] 的格式例如是“12”和“123”表示该项目位于 ID 为 1、2 和 3 的存储库中

我得到的错误

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:643)
at java.util.ArrayList.add(ArrayList.java:455)
at dadsaassi.manager.addRep(manager.java:26)

Java 结果:1我的项目类

public int itemNum = 0;
public String des = "";
public int price = 0;

public Item(int i, String d, int p) {
itemNum = i;
des = d;
price = p;
}

我的经理类

private ArrayList<Item> rep = new ArrayList<Item>();
private ArrayList<Item> list = new ArrayList<Item>(); //creates ArrayList

public void addItems(Item item) {
list.add(item);
}

public void addRep(int num, Item item) {
rep.add(num, item);

最佳答案

List基于 0 索引。在 manager.java ,每当您尝试添加 rep 的 1 个索引时ArrayList比rep.size()>0true .

 m.addItemToRepository(1, item);

因此,它会抛出 IndexOutOfBoundsException。查看 List.add(element, index) 的文档方法。

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

解决方案是,您不应该在 rep 处提及索引列表

 m.addItemToRepository(item); //It will start from 0

或者,

m.addItemToRepository(0, item);// Although index is here redundant.

编辑:如果你需要版本号,你也可以使用Map<Integer, Item> , 其中Integer是存储库编号。

Map<Integer, Item> rep = new HashMap<Integer, Item>();

public void addItemToRepository(int num, Item item) {
rep.put(num, item);
}

关于java - Java新手。如何使用文本文件将项目添加到特定存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29248873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com