Integer Math


Let's revisit the code in the class Performance (from Lesson 7) that calculates the average for a series of tests.

 public double average() {    double total = 0.0;    for (int score: tests)       total += score;    return total / tests.length; } 

Suppose the total local variable had been declared as an int instead of a double, which is reasonable since each test score is an int. Adding an int to an int returns another int.

 public double average() {    int total = 0;    for (int score: tests)       total += score;    return total / tests.length; } 

This seemingly innocuous change will break several tests in PerformanceTest. The problem is, dividing an int by an int also returns an int. Integer division always produces integer results; any remainders are discarded. The following two assertions demonstrate correct integer division:

 assertEquals(2, 13 / 5); assertEquals(0, 2 / 4); 

If you need the remainder while doing integer division, use the modulus operator (%).

 assertEquals(0, 40 % 8); assertEquals(3, 13 % 5); 



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net