📌  相关文章
📜  Java番石榴 | IntMath.checkedSubtract(int a, int b) 方法与示例

📅  最后修改于: 2022-05-13 01:55:20.947000             🧑  作者: Mango

Java番石榴 | IntMath.checkedSubtract(int a, int b) 方法与示例

checkedSubtract(int a, int b)是 Guava 的 IntMath 类的一种方法,它接受两个参数ab ,并返回它们的差值。

句法:

public static int checkedSubtract(int a, int b)

参数:该方法接受两个 int 值ab并计算它们的差。

返回值:该方法返回传递给它的 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

参考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#checkedSubtract-int-int-