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