Java扫描仪解析输入

Java Scanner parsing input

我有以下输入字符串:

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

我想使用 Java 扫描仪 class 解析此输入以创建产品对象列表。

请注意输入行包含多个产品(在本例中为两个),如下所示:

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?

谢谢。

我会在 space 上使用拆分,这是 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);
}

希望对您有所帮助。