Java Integer.compare()方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-compare-method

Java compare()方法属于Integer 类。此方法用于比较两个整数的数值,找出哪个大于另一个。

compare(int x,int y) 方法返回该值

  • 0 ;如果 x 和 y 的值相等。
  • -1 ;如果 x 的值小于 y。
  • 1;如果 x 的值大于 y。

语法:

public static int compare(int x, int y)

参数:

传递的参数由两个整数int xint y 组成,分别表示要比较的第一个和第二个整数。

返回:

根据 x 和 y 的值,返回值 0,1,-1。

例 1:

这里,取四个整数 n1、n2、n3、n4,取其各自的正值,并检查其值是小于、大于还是等于比较值。

import java.lang.Integer;

public class StudyTonight 
{  
    public static void main(String[] args) 
     {          
      int n1 = 100;  
      int n2 = 200;  
      int n3 = 300;  
      int n4 = 100;  

        System.out.println(Integer.compare(n1, n2));  //Output will be less than zero

        System.out.println(Integer.compare(n3, n1)); // Output will be greater than zero  

        System.out.println(Integer.compare(n1,n4));  // Output will be equal to zero
      }  
}

-1 1 0

例 2:

这里,在一个数组中取四个整数 n1、n2、n3、n4,并检查其值与数组的第一个值相比是少、多还是相等。

import java.lang.Integer;

public class StudyTonight 
{  
    public static void main(String[] args) 
    {          
      int []n = {-100,-200,300,-100};  

       for(int i=0;i<4;i++)

       {
          System.out.println(Integer.compare(n[0], n[i]));  

       }  
    } 
}

0 1 -1 0

例 3:

这里有一个通用的例子,用户可以输入他选择的数字并获得所需的输出。trycatch块用于处理程序执行期间发生的任何异常。(例如,用户输入字符串等。代替整数)。

import java.util.Scanner; 
import java.lang.Integer;
public class StudyTonight 
{  
    public static void main(String[] args) 
    {      
        Scanner sc = new Scanner(System.in);  
        System.out.print("Enter first and second number ");  
          try
          {
           int n1 = sc.nextInt();  
           int n2 = sc.nextInt();  
           int r =  Integer.compare(n1, n2);    
             if(r > 0)
              {  
               System.out.println("first number is greater");  
              }
              else if(r< 0) 
              {  
                System.out.println("second number is greater");  
              } 
              else
              {  
               System.out.println("both numbers are equal");
              }
           }
          catch(Exception e)
           {
            System.out.println("Error!!");
           }

      }  
 }

输入第一个和第二个数字 100 452 第二个数字大于

输入第一个和第二个数字 0x789 890 错误!!

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。