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

我正在尝试让一个类用几行来读取我的 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 知道这个和这个索引之间是名称,这个和这个索引之间是产品号?


谢谢大家真的很感激。


梵蒂冈之花
浏览 171回答 2
2回答

撒科打诨

由于这些行是以逗号分隔的列表,您可以使用split()该行将行拆分为单个变量。另一件需要考虑的事情是Scanner("file.txt")不读取指定的文本文件,而只读取给定的String. 您必须先创建一个File对象。File input = new File("Desktop/Lotion.txt");Scanner scanner;scanner = new Scanner(input);while(scanner.hasNext()){&nbsp; &nbsp; String readLine = scanner.nextLine();&nbsp; &nbsp; String[] strArray = readLine.split(",");&nbsp; &nbsp; int indexOfProductNo = Integer.parseInt(strArray[1].trim());&nbsp; &nbsp; int indexOfProductRating = Integer.parseInt(strArray[2].trim());&nbsp; &nbsp; double indexOfProductDiscount = Double.parseDouble(strArray[3].trim());&nbsp; &nbsp; lotion.add(new Lotion(strArray[0],indexOfProductNo,indexOfProductRating,indexOfProductDiscount));}

杨魅力

您可以使用正则表达式(Demo):([\w\s]+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+(?:\.\d+))您可以将其定义为班级中的常量:private static final Pattern LOTION_ENTRY =&nbsp;&nbsp; &nbsp; Pattern.compile("([\\w\\s]+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+(?:\\.\\d+))");然后你可以Matcher为每个条目创建一个并提取组:Matcher matcher = LOTION_ENTRY.matcher(readLine);if(matcher.matches()) {&nbsp; &nbsp; String name = matcher.group(1);&nbsp; &nbsp; int no = Integer.parseInt(matcher.group(2));&nbsp; &nbsp; int rating = Integer.parseInt(matcher.group(3));&nbsp; &nbsp; double discount = Double.parseDouble(matcher.group(4));&nbsp; &nbsp; // do something} else {&nbsp; &nbsp; // line doesn't match pattern, throw error or log}不过请注意:如果输入无效,则parseInt()andparseDouble可以抛出 a 。NumberFormatException所以你必须抓住那些并采取相应的行动。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java