我正在尝试让一个类用几行来读取我的 txt 文件,例如:
洗面奶, 1 , 2, 0.1
保湿乳液, 2, 3, 0.2
爽肤水, 3, 4, 0.3
芦荟乳液, 4, 5, 0.4
我创建了一个具有属性名称(字符串)、productNo(int)、productRating(int) 和 productDiscount(double) 的类调用 Lotion,我创建了另一个类调用 ListOfLotion 并添加到 Lotion 的数组列表中。
我的问题是如何让我的 ListOfLotion 类使用 txt 文件中的值并将其放入我的数组列表中。
我尝试使用 indexOf 作为名称直到下一个,但出现错误,java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 17
无论如何我也可以分开所有四个值并确保它们正确存储,例如,面部乳液存储为名称,1 存储为 prodcuctNo。
public void addListOfLotion(){
ArrayList<Lotion> lotion = new ArrayList<Lotion>();
Scanner scanner = new Scanner("Desktop/Lotion.txt");
while(scanner.hasNext()){
String readLine = scanner.nextLine();
int indexProductNo = readLine.indexOf(',');
int indexOfProductRating = readLine.indexOf(',');
double indexOfProductDiscount = readLine.indexOf(',');
lotion.add(new Lotion(readLine.substring(0, indexOfProductNo),0,0,0));
}scanner.close();
}
Got this error as result:
java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 17
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at ListOfVenues.addListOfLotion(ListOfLotion.java:42)
是因为我把 readLine,indexOf(',') 作为每个 readLine,它只是停在第一个 ',' 处吗?无论如何,我可以有效地让 java 知道这个和这个索引之间是名称,这个和这个索引之间是产品号?
谢谢大家真的很感激。
梵蒂冈之花
撒科打诨
杨魅力
随时随地看视频慕课网APP
相关分类