[英]Parsing a text file using java bufferedReader and Scanner
[英]Java Scanner parsing input
我有以下輸入字符串:
1 imported box of chocolates at 10.00 1 imported bottle of perfume at 47.50
例如,我想使用 Java Scanner 類來解析此輸入以創建產品對象列表。
請注意輸入行由多個產品(在本例中為兩個)組成,如下所示:
Quantity: 1
Name: imported box of chocolates
Price: 10.00
Quantity: 1
Name: imported bottle of perfume
Price: 47.50
理想情況下,我想解析該行的第一個產品部分,然后解析下一個產品部分。
我知道如何使用正則表達式等來做到這一點,但問題是:
What is the best way to use the Java Scanner to parse the input line?
謝謝你。
我只會在空間上使用分割,這是 Scanner 默認所做的,並根據以下規則自己進行解析。
ORDER := QUANTITY DESCRIPTION at PRICE ORDER | ""
QUANTITY := Integer
DESCRIPTION := String
PRICE := Float
為簡單起見,您可以像下面那樣進行,當然您必須包含一些錯誤處理。 更好的選擇是使用像 antlr 這樣的工具,它可以為您完成所有繁重的工作。
Scanner sc = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<>();
while (sc.hasNext()) {
int quantity = sc.nextInt();
StringBuilder description = new StringBuilder();
while (!(String token = sc.next()).equals("at")) {
description.append(token);
}
float price = sc.nextFloat();
Product p = new Product(quantity, description.toString(), price);
products.add(product);
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.