Combine normalized values and a pure decimal calculation. This checkpoint computes an invoice total from quantities and unit prices. Each line is validated once, and reporting reads those valid values without changing them. No tax or real accounting policy is implied.
Understand the contract
The contract permits quantity 1–100 and unit prices greater than zero with at most two meaningful decimal places. A line total is exact price multiplied by the integer quantity. Multiplication by BigDecimal.valueOf(quantity) preserves the decimal representation; quantity is an exact integer, not a floating-point estimate.
An invoice accepts an empty list and returns 0.00. It does not silently omit a malformed line: such a line should never be constructed. The input list and its line objects are nonnull. In the final project, parsing will turn external text into validated values before a report sees them.
The worked example starts with an already-valid line and shows the arithmetic. The second example shows why rounding every contribution is a different policy from rounding the total. For this checkpoint, extra precision is rejected at the boundary so that ambiguity cannot enter the calculation.
Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal unitPrice = new BigDecimal("1.25");
int quantity = 3;
BigDecimal lineTotal = unitPrice.multiply(BigDecimal.valueOf(quantity));
System.out.println(lineTotal);
System.out.println(unitPrice);
}
}Check your prediction
3.75
1.25Trace a different case
Rounding is not generally distributive over addition. Two 0.005 contributions rounded individually with HALF_UP produce 0.02, while their exact sum rounded once produces 0.01. Neither choice should be hidden in an incidental formatting call. Here this is a demonstration of policy differences, not acceptable input for the invoice.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
BigDecimal part = new BigDecimal("0.005");
BigDecimal separately = part.setScale(2, RoundingMode.HALF_UP)
.add(part.setScale(2, RoundingMode.HALF_UP));
BigDecimal together = part.add(part).setScale(2, RoundingMode.HALF_UP);
System.out.println(separately);
System.out.println(together);
}
}Check your prediction
0.02
0.01Plan your acceptance cases
Before writing the complete implementation, predict these cases without running the solution. Keep the requirements above as the authority; this table highlights distinct promises rather than prescribing a particular class layout.
| Case | Expected behavior | Skill it checks |
|---|---|---|
| 1.25 × 3 plus 2.00 × 2 | 7.75 | Exact multiplication and reduction |
| Price 1.001 or quantity 0 | Reject construction | Precision and range |
| Empty invoice | 0.00 | Reduction identity |
After your first version works, choose one row and introduce a plausible defect that it should expose. Restore the correct version, then recreate the central operation without the worked example. If one skill is missing, revisit that lesson before combining more features.
Build it yourself
Checkpoint: Invoice Total: practice
Implement record Line(BigDecimal price, int quantity) with the stated validation and a total() method. Write invoiceTotal(List<Line>) returning a two-place exact total. Demonstrate prices 1.25 × 3 and 2.00 × 2 giving 7.75, and empty input giving 0.00. Add rejection checks for zero quantity and price 1.001 before accepting your solution.
public class Main {
public static void main(String[] args) {
// Add your implementation and checks below.
System.out.println("Your workspace");
}
}Hint 1: the idea
Keep line validity inside construction. The report only multiplies and adds valid values.
Hint 2: a first step
Normalize price in the compact constructor, and start the invoice accumulator at 0.00.
Show one solution
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println(invoiceTotal(List.of(new Line(new BigDecimal("1.25"), 3), new Line(new BigDecimal("2"), 2))));
System.out.println(invoiceTotal(List.of()));
for (int quantity : new int[] {0, 101}) {
try {
new Line(BigDecimal.ONE, quantity);
throw new AssertionError("quantity accepted");
} catch (IllegalArgumentException expected) {
// Expected rejection.
}
}
try {
new Line(new BigDecimal("1.001"), 1);
throw new AssertionError("precision accepted");
} catch (IllegalArgumentException expected) {
// Expected rejection.
}
}
static BigDecimal invoiceTotal(List<Line> lines) {
return lines.stream()
.map(Line::total)
.reduce(new BigDecimal("0.00"), BigDecimal::add);
}
}
record Line(BigDecimal price, int quantity) {
Line {
if (price == null || price.signum() <= 0 || quantity < 1 || quantity > 100) {
throw new IllegalArgumentException("invalid line");
}
try {
price = price.setScale(2, RoundingMode.UNNECESSARY);
} catch (ArithmeticException error) {
throw new IllegalArgumentException("price precision", error);
}
}
BigDecimal total() {
return price.multiply(BigDecimal.valueOf(quantity));
}
}Expected output:
7.75
0.00Validation and scale both live in Line's constructor, so invoiceTotal can
trust every line and stay a plain reduction. The identity is new BigDecimal("0.00"), not BigDecimal.ZERO: that is why the empty invoice prints
0.00 rather than 0. Prices are rescaled with UNNECESSARY, so 1.001 is rejected
instead of rounded, and price * quantity stays exact at two places.
Change it and test again
Check quantity 100, a price with redundant trailing zeros, and a single line. Deliberately use addition instead of multiplication in total(): choose a quantity that catches it. Add an invoice with repeated identical lines and confirm both contribute; repetition is meaningful here, unlike a duplicate unique ID.
Explain before moving on
Which guarantees come from record syntax, validation, BigDecimal arithmetic and the test cases? Explain why this invoice has no stored running total to become stale. Before moving on, be able to write the loop equivalent of the stream report.
Completion is saved in this browser only. It does not measure mastery.