19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

398 Chapter 10 Thinking in Objects<br />

There is no limit <strong>to</strong> the precision of a BigDecimal object. The divide method may throw<br />

an ArithmeticException if the result cannot be terminated. However, you can use<br />

the overloaded divide(BigDecimal d, int scale, int roundingMode) method <strong>to</strong><br />

specify a scale and a rounding mode <strong>to</strong> avoid this exception, where scale is the maximum<br />

number of digits after the decimal point. For example, the following code creates two<br />

BigDecimal objects and performs division with scale 20 and rounding mode<br />

BigDecimal.ROUND_UP.<br />

BigDecimal a = new BigDecimal(1.0);<br />

BigDecimal b = new BigDecimal(3);<br />

BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);<br />

System.out.println(c);<br />

The output is 0.33333333333333333334.<br />

Note that the fac<strong>to</strong>rial of an integer can be very large. Listing 10.11 gives a method that can<br />

return the fac<strong>to</strong>rial of any integer.<br />

constant<br />

multiply<br />

LISTING 10.11<br />

LargeFac<strong>to</strong>rial.java<br />

1 import java.math.*;<br />

2<br />

3 public class LargeFac<strong>to</strong>rial {<br />

4 public static void main(String[] args) {<br />

5 System.out.println("50! is \n" + fac<strong>to</strong>rial(50));<br />

6 }<br />

7<br />

8 public static BigInteger fac<strong>to</strong>rial(long n) {<br />

9 BigInteger result = BigInteger.ONE;<br />

10 for (int i = 1; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!