當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Integer max()用法及代碼示例

max() 是Java.lang 包下Integer 類的一個方法。此方法以數字方式返回用戶指定的兩個方法參數之間的最大值。這個方法可以被重載,它接受 int、double、float 和 long 中的參數。此方法由 Math 類指定。

注意:如果將正數和負數作為參數傳遞,則生成正數結果。如果兩個參數都作為負數傳遞,它會生成具有較低量級的結果。

用法:

以下是 max() 方法的聲明:

public static int max(int a, int b)
public static long max(long a, long b)
public static float max(float a, float b)
public static double max(double a, double b)

參數:

數據類型 參數 描述 必需/可選
int a 用戶輸入的數值。 Required
int b 用戶輸入的數值。 Required

返回值:

max() 方法返回用戶指定的兩個方法參數之間的較大值。

異常:

NA

兼容版本:

Java 1.5 及以上

例子1

public class IntegerMaxExample1 {
    public static void main(String[] args) {
        // get two integer numbers
          int x = 5485;
          int y = 3242;   
          // print the larger number between x and y
          System.out.println("Math.max(" + x + "," + y + ")=" + Math.max(x, y));
    }
}

輸出:

Math.max(5485,3242)=5485

例子2

import java.util.Scanner;
public class IntegerMaxExample2 {
    public static void main(String[] args) {
        //Get two integer numbers from console
        System.out.println("Enter the Two Numeric value:");
        Scanner readInput= new Scanner(System.in);
        int a = readInput.nextInt();
        int b = readInput.nextInt();
        readInput.close();			   
          //Print the larger number between a and b
          System.out.println("Larger value of Math.max(" + a + "," + b + ") = " + Math.max(a, b));
    }
}

輸出:

Enter the Two Numeric value:
45
77
Larger value of Math.max(45,77) = 77

例子3

public class IntegerMaxExample3 {
    public static void main(String[] args) {
      //Get two integer numbers
      int a = -25;
        int b = -23;
        // Prints result with lower magnitude
        System.out.println("Result:"+Math.max(a, b));
    }
}

輸出:

Result:-23

示例 4

public class IntegerMaxExample4 {
    public static void main(String[] args) {
        //Get two integer numbers
        int a = -75;
            int b = 23;
            // Prints result with positive value
            System.out.println("Result:"+Math.max(a, b));
    }
}

輸出:

Result:23






相關用法


注:本文由純淨天空篩選整理自 Java Integer max() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。