Real World Example

Parsing an Order CSV Line

E-commerce systems import orders from CSV files sent by sellers. Each column arrives as text and must be converted to numbers safely; a missing discount stays null (unknown) instead of 0.

Example

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> lines = List.of(
                "ORD-1,Headphones,2,1499.00,10",
                "ORD-2,Charger,1,599.50,",
                "ORD-3,Cable,two,199.00,5");
        for (String line : lines) {
            try {
                String[] c = line.split(",", -1);
                int qty = Integer.parseInt(c[2]);
                double price = Double.parseDouble(c[3]);
                Integer discount = c[4].isEmpty() ? null : Integer.valueOf(c[4]);
                double total = qty * price;
                if (discount != null) {
                    total -= total * discount / 100;
                }
                System.out.printf("%s %-10s qty=%d discount=%s total=%.2f%n",
                        c[0], c[1], qty, discount == null ? "none" : discount + "%", total);
            } catch (NumberFormatException e) {
                System.out.println("Skipping bad line: " + line + " (" + e.getMessage() + ")");
            }
        }
    }
}

Output

ORD-1 Headphones qty=2 discount=10% total=2698.20
ORD-2 Charger    qty=1 discount=none total=599.50
Skipping bad line: ORD-3,Cable,two,199.00,5 (For input string: "two")