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


Java Short compareUnsigned()用法及代碼示例

Java Short 類的 CompareUnsigned() 方法用於對兩個 Short 值進行數值比較,並將每個 Short 值視為無符號。這個方法是從 jdk 1.9 開始添加的。

用法

public static int compareUnsigned(short x,short y)

參數

它需要 Short 類型參數。

X:要比較的第一個 Short 值

Y:要比較的第二個 Short 值

返回值

  • 如果 Short x 的無符號值等於 Short y 的值,則返回 0。
  • 如果 Short x 的無符號值小於 Short y 的值,則返回小於 0。
  • 如果 Short x 的無符號值大於 Short y 的值,則返回大於 0。

例子1

如果 Short x 的無符號值等於 Short y 的值。

public class ShortCompareUnsignedExample1 {  
public static void main(String[] args) {   //both value is same   
Short s1 = 60;   
Short s2 = 60;   // Implementing compareUnsigned() method   
int result=Short.compareUnsigned( s1, s2);      
System.out.println(" when s1= "+s1+" and s2= "+s2+" is Same then result:"+result);  
} 
}

輸出:

when s1= 60 and s2= 60 is Same then result:0 

例子2

如果 Short x 的無符號值小於 Short y 的值。

public class ShortCompareUnsignedExample2 {  
public static void main(String[] args) {   //both value is not same   
Short s1 = 70;   Short s2 = 90;   // Implementing compareUnsigned() method   
int result=Short.compareUnsigned( s1, s2);   
System.out.println(" when s1= "+s1+" is less than s2= "+s2+" , then result:"+result); 
  } 
}

輸出:

when s1= 70 is less than s2= 90 , then result:-20 

例子3

如果 Short x 的無符號值大於 Short y 的值。

public class ShortCompareUnsignedExample3 {  
public static void main(String[] args) {   
//both value is not same   Short s1 = 70;   
Short s2 = 60;   // Implementing compareUnsigned() method   
int result=Short.compareUnsigned( s1, s2);   
System.out.println(" when s1= "+s1+" is greater than s2= "+s2+" , then result:"+result);  
}
}

輸出:

when s1=70 is greater than s2=60 , then result:10






相關用法


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