Java Long.compare()方法

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

Java compare()方法属于Long类。此方法用于对两个长值进行数值比较,以找出哪一个大于另一个。

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

  • 0 ,如果 x 和 y 的值相等。

  • -1 ,如果 x 的值小于 y。

  • 1 ,如果 x 的值大于 y。

语法:

public static int compare(long x, long y)

参数:

传递的参数由两个长值long xlong y组成,分别代表要比较的第一个和第二个值。

返回:

根据xy的值返回 0,1,-1。

例 1:

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

import java.lang.Long;

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

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

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

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

-1 1 0

例 2:

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

import java.lang.Long;

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

        for(int i=0;i<4;i++)
        {
            System.out.println(Long.compare(n[0], n[i]));  
        }  
    } 
}

0 1 -1 0

例 3:

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

import java.util.Scanner; 
import java.lang.Long;

public class StudyTonight 
{  
    public static void main(String[] args) 
    {      
        Scanner sc = new Scanner(System.in);  
        System.out.print("Enter first and second number ");  
        try
        {
            long n1 = sc.nextLong();  
            long n2 = sc.nextLong();  
            int r =  Long.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!!");
        }  
    }  
}

输入第一个和第二个数字 90 567 第二个数字更大 *输入第一个和第二个数字 678 44 第一个数字更大 *输入第一个和第二个数字 0x56 0x533 错误!!

实时示例:

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