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));
}
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所以你必须抓住那些并采取相应的行动。
添加回答
举报
