Skip to content

Instantly share code, notes, and snippets.

@YukiYoshikawa
Last active December 16, 2015 14:48
Show Gist options
  • Save YukiYoshikawa/5450871 to your computer and use it in GitHub Desktop.
Save YukiYoshikawa/5450871 to your computer and use it in GitHub Desktop.
package trial.yy.guava.client.math;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
/**
* com.google.common.math.IntMath,LongMathを試すためのサンプル
* User: yy
*/
public class MathClient {
public static void main(String[] args) {
// 単純に四則演算するとオーバーフローが起こるが、一応(期待しない)計算結果が返ってくる
System.out.printf("%d + %d = %d\n", Integer.MAX_VALUE, 1, Integer.MAX_VALUE + 1);
System.out.printf("%d - %d = %d\n", Integer.MIN_VALUE, 1, Integer.MIN_VALUE - 1);
System.out.printf("%d * %d = %d\n", Integer.MAX_VALUE, 5, Integer.MAX_VALUE * 5);
System.out.println("###");
// オーバーフローをチェックしながら加算・減算・乗算を行う
// オーバーフローした場合はArithmeticExceptionがスローされる
// 加算
System.out.printf("%d + %d = %d\n", 2, 3, IntMath.checkedAdd(2, 3));
try {
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
System.out.printf("%d + %d = %s\n", Integer.MAX_VALUE, 1, e.getMessage());
}
// 減算
System.out.printf("%d - %d = %d\n", 5, 4, IntMath.checkedSubtract(5, 4));
try {
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
} catch (ArithmeticException e) {
System.out.printf("%d - %d = %s\n", Integer.MIN_VALUE, 1, e.getMessage());
}
// 乗算
System.out.printf("%d * %d = %d\n", 10, 2, IntMath.checkedMultiply(10, 2));
try {
IntMath.checkedMultiply(Integer.MAX_VALUE, 5);
} catch (ArithmeticException e) {
System.out.printf("%d * %d = %s\n", Integer.MAX_VALUE, 5, e.getMessage());
}
System.out.println("###");
// Long値用の同様のクラス(LongMath)を使用した計算
// 加算
System.out.printf("%d + %d = %d\n", 20L, 30L, LongMath.checkedAdd(20L, 30L));
try {
LongMath.checkedAdd(Long.MAX_VALUE, 1L);
} catch (ArithmeticException e) {
System.out.printf("%d + %d = %s\n", Long.MAX_VALUE, 1, e.getMessage());
}
// 減算
System.out.printf("%d - %d = %d\n", 50L, 40L, LongMath.checkedSubtract(50L, 40L));
try {
LongMath.checkedSubtract(Long.MIN_VALUE, 1L);
} catch (ArithmeticException e) {
System.out.printf("%d - %d = %s\n", Long.MIN_VALUE, 1L, e.getMessage());
}
// 乗算
System.out.printf("%d * %d = %d\n", 100L, 20L, LongMath.checkedMultiply(100L, 20L));
try {
LongMath.checkedMultiply(Long.MAX_VALUE, 5L);
} catch (ArithmeticException e) {
System.out.printf("%d * %d = %s\n", Long.MAX_VALUE, 5L, e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment