java multiply_Java IntMath.checkedMultiply(int a, int b)用法及代码示例

CheckedMultiply(int a,int b)是Guava IntMath类的方法,该方法接受两个参数a和b并返回其乘积。

用法:

public static int checkedMultiply(int a, int b)

参数:该方法接受两个int值a和b并计算它们的乘积。

返回值:该方法返回传递给它的int值的乘积,前提是它不会溢出。

异常:如果乘积(a-b)在有符号的int算术中溢出,则checkedMultiply(int a,int b)的方法将引发ArithmeticException。

以下示例说明了上述方法的实现:

范例1:

// Java code to show implementation of

// checkedMultiply(int a, int b) method

// of Guava's IntMath class

import java.math.RoundingMode;

import com.google.common.math.IntMath;

class GFG {

// Driver code

public static void main(String args[])

{

int a1 = 25;

int b1 = 36;

// Using checkedMultiply(int a, int b)

// method of Guava's IntMath class

int ans1 = IntMath.checkedMultiply(a1, b1);

System.out.println("Product of " + a1 + " and "

+ b1 + " is:" + ans1);

int a2 = 150;

int b2 = 667;

// Using checkedMultiply(int a, int b)

// method of Guava's IntMath class

int ans2 = IntMath.checkedMultiply(a2, b2);

System.out.println("Product of " + a2 + " and "

+ b2 + " is:" + ans2);

}

}

输出:

Product of 25 and 36 is:900

Product of 150 and 667 is:100050

范例2:

// Java code to show implementation of

// checkedMultiply(int a, int b) method

// of Guava's IntMath class

import java.math.RoundingMode;

import com.google.common.math.IntMath;

class GFG {

static int findDiff(int a, int b)

{

try {

// Using checkedMultiply(int a, int b) method

// of Guava's IntMath class

// This should throw "ArithmeticException"

// as the product overflows in signed

// int arithmetic

int ans = IntMath.checkedMultiply(a, b);

// Return the answer

return ans;

}

catch (Exception e) {

System.out.println(e);

return -1;

}

}

// Driver code

public static void main(String args[])

{

int a = Integer.MIN_VALUE;

int b = 452;

try {

// Function calling

findDiff(a, b);

}

catch (Exception e) {

System.out.println(e);

}

}

}

输出:

java.lang.ArithmeticException:overflow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值