jakstack
jakstack

Reputation: 2205

Java Scanner parsing input

I have the the following input string:

1 imported box of chocolates at 10.00 1 imported bottle of perfume at 47.50

I would like to use the Java Scanner class to parse this input to create a list of product objects for example.

Please note the input line consists of multiple products (two in this case) as follows:

Quantity: 1
Name: imported box of chocolates
Price: 10.00

Quantity: 1
Name: imported bottle of perfume
Price: 47.50

Ideally I would like to parse the first product portion of the line and then the next product portion.

I know how to do this using regex etc but the question is:

What is the best way to use the Java Scanner to parse the input line?

Thank you.

Upvotes: 0

Views: 3390

Answers (1)

turingcomplete
turingcomplete

Reputation: 2188

I would just use splitting on space which is what Scanner does by default, and do the parsing myself according to the following rule.

ORDER := QUANTITY DESCRIPTION at PRICE ORDER | "" 
QUANTITY := Integer
DESCRIPTION := String
PRICE := Float

For simplicity you can do it like below, you will have to include some error handling of course. A better option would be to use a tool like antlr which will do all the heavy lifting for you.

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);
}

Hope this helps.

Upvotes: 1

Related Questions