为了账号安全,请及时绑定邮箱和手机立即绑定

如果我有多个属性,如何读取txt文件?

如果我有多个属性,如何读取txt文件?

梵蒂冈之花 2022-11-30 13:26:21
我正在尝试让一个类用几行来读取我的 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 知道这个和这个索引之间是名称,这个和这个索引之间是产品号?谢谢大家真的很感激。
查看完整描述

2 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

由于这些行是以逗号分隔的列表,您可以使用split()该行将行拆分为单个变量。

另一件需要考虑的事情是Scanner("file.txt")不读取指定的文本文件,而只读取给定的String. 您必须先创建一个File对象。


File input = new File("Desktop/Lotion.txt");

Scanner scanner;

scanner = new Scanner(input);

while(scanner.hasNext()){

    String readLine = scanner.nextLine();

    String[] strArray = readLine.split(",");

    int indexOfProductNo = Integer.parseInt(strArray[1].trim());

    int indexOfProductRating = Integer.parseInt(strArray[2].trim());

    double indexOfProductDiscount = Double.parseDouble(strArray[3].trim());

    lotion.add(new Lotion(strArray[0],indexOfProductNo,indexOfProductRating,indexOfProductDiscount));

}


查看完整回答
反对 回复 2022-11-30
?
杨魅力

TA贡献1811条经验 获得超6个赞

您可以使用正则表达式(Demo):


([\w\s]+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+(?:\.\d+))

您可以将其定义为班级中的常量:


private static final Pattern LOTION_ENTRY = 

    Pattern.compile("([\\w\\s]+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+(?:\\.\\d+))");

然后你可以Matcher为每个条目创建一个并提取组:


Matcher matcher = LOTION_ENTRY.matcher(readLine);


if(matcher.matches()) {

    String name = matcher.group(1);

    int no = Integer.parseInt(matcher.group(2));

    int rating = Integer.parseInt(matcher.group(3));

    double discount = Double.parseDouble(matcher.group(4));


    // do something

} else {

    // line doesn't match pattern, throw error or log

}

不过请注意:如果输入无效,则parseInt()andparseDouble可以抛出 a 。NumberFormatException所以你必须抓住那些并采取相应的行动。


查看完整回答
反对 回复 2022-11-30
  • 2 回答
  • 0 关注
  • 170 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号