CheckedSubtract(int a,int b)是Guava IntMath类的方法,该方法接受两个参数a和b,并返回它们的差值。
用法:
public static int checkedSubtract(int a, int b)
参数:该方法接受两个int值a和b并计算它们的差。
返回值:该方法返回传递给它的int值的差,前提是它不会溢出。
异常:如果差异(即a-b)在有符号的int算术中溢出,则checkedSubtract(int a,int b)的方法将引发ArithmeticException。
以下示例说明了上述方法的实现:
范例1:
// Java code to show implementation of
// checkedSubtract(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 checkedSubtract(int a, int b)
// method of Guava's IntMath class
int ans1 = IntMath.checkedSubtract(a1, b1);
System.out.println("Difference of " + a1 + " and "
+ b1 + " is:" + ans1);
int a2 = 150;
int b2 = 667;
// Using checkedSubtract(int a, int b)
// method of Guava's IntMath class
int ans2 = IntMath.checkedSubtract(a2, b2);
System.out.println("Difference of " + a2 + " and "
+ b2 + " is:" + ans2);
}
}
输出:
Difference of 25 and 36 is:-11 Difference of 150 and 667 is:-517
范例2:
// Java code to show implementation of
// checkedSubtract(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 checkedSubtract(int a, int b) method
// of Guava's IntMath class
// This should throw "ArithmeticException"
// as the difference overflows in signed
// int arithmetic
int ans = IntMath.checkedSubtract(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
相关用法
- Java Guava Floats.max()用法及代码示例
- Java Guava Booleans.contains()用法及代码示例
- Java Guava Chars.max()用法及代码示例
- Java Guava Chars.contains()用法及代码示例
- Java Guava Doubles.min()用法及代码示例
- Java Guava Doubles.contains()用法及代码示例
- Java Guava Shorts.min()用法及代码示例
- Java Guava Bytes.contains()用法及代码示例
- Java Guava Longs.contains()用法及代码示例
- Java Guava Floats.contains()用法及代码示例
- Java Guava Longs.min()用法及代码示例
- Java Guava Chars.min()用法及代码示例
- Java Guava Shorts.max()用法及代码示例
- Java Guava Doubles.max()用法及代码示例
- Java Guava Longs.max()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Java Guava | IntMath.checkedSubtract(int a, int b) method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。