IntMath提供整型的實用方法。
以下是com.google.common.math.IntMath類的聲明:
@GwtCompatible(emulated=true)
public final class IntMath
? ?extends Object
方法
方法繼承
這個類從以下類繼承的方法: java.lang.Object
選擇使用任何編輯器創(chuàng)建以下java程序在 C:/> Guava
GuavaTester.java
import java.math.RoundingMode;
import com.google.common.math.IntMath;
public class GuavaTester {
public static void main(String args[]){
GuavaTester tester = new GuavaTester();
tester.testIntMath();
}
private void testIntMath(){
try{
System.out.println(IntMath.checkedAdd(Integer.MAX_VALUE, Integer.MAX_VALUE));
}catch(ArithmeticException e){
System.out.println("Error: " + e.getMessage());
}
System.out.println(IntMath.divide(100, 5, RoundingMode.UNNECESSARY));
try{
//exception will be thrown as 100 is not completely divisible by 3 thus rounding
// is required, and RoundingMode is set as UNNESSARY
System.out.println(IntMath.divide(100, 3, RoundingMode.UNNECESSARY));
}catch(ArithmeticException e){
System.out.println("Error: " + e.getMessage());
}
System.out.println("Log2(2): "+IntMath.log2(2, RoundingMode.HALF_EVEN));
System.out.println("Log10(10): "+IntMath.log10(10, RoundingMode.HALF_EVEN));
System.out.println("sqrt(100): "+IntMath.sqrt(IntMath.pow(10,2), RoundingMode.HALF_EVEN));
System.out.println("gcd(100,50): "+IntMath.gcd(100,50));
System.out.println("modulus(100,50): "+IntMath.mod(100,50));
System.out.println("factorial(5): "+IntMath.factorial(5));
}
}
驗證結(jié)果
使用javac編譯器編譯如下類
C:\Guava>javac GuavaTester.java
現(xiàn)在運(yùn)行GuavaTester看到的結(jié)果
C:\Guava>java GuavaTester
看到結(jié)果
Error: overflow
20
Error: mode was UNNECESSARY, but rounding was necessary
Log2(2): 1
Log10(10): 1
sqrt(100): 10
gcd(100,50): 50
modulus(100,50): 0
factorial(5): 120
轉(zhuǎn)載自并發(fā)編程網(wǎng)-ifeve.com