Java Integer.compareUnsigned()方法

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

Java compareUnsigned()方法属于java.lang包的Integer 类,由**Comparable<Integer>**接口指定。此方法用于比较传递的两个整数的无符号值,以找出哪一个大于另一个。

compareUnsigned(int x,int y) 方法返回值:

  • 0;如果 x 和 y 的无符号值相等。

  • -1;如果 x 的无符号值小于 y。

  • 1;如果 x 的无符号值大于 y。

语法:

public static int compareUnsigned(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.compareUnsigned(n1, n2));  //Output will be less than zero

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

        System.out.println(Integer.compareUnsigned(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.compareUnsigned(n[0], n[i]));  

       }  
    } 
}

0 1 1 1

例 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.compareUnsigned(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!!");
           }

      }  
 }

输入第一个和第二个数字-34 98 第一个数字较大

实时示例:

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