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所以你必須抓住那些并采取相應的行動。
添加回答
舉報