2015-10-19 110 views
0

我有以下輸入字符串:Java的掃描儀解析輸入

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? 

謝謝。

回答

1

我只是在空間上使用分割,這是默認情況下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); 
} 

希望這會有所幫助。