Groovy - 關係運算符



關係運算符允許比較物件。以下是 Groovy 中可用的關係運算符:

運算子 描述 示例
== 測試兩個物件之間的相等性 2 == 2 將返回 true
!= 測試兩個物件之間的差異 3 != 2 將返回 true
< 檢查左側物件是否小於右側運算元。 2 < 3 將返回 true
<= 檢查左側物件是否小於或等於右側運算元。 2 <= 3 將返回 true
> 檢查左側物件是否大於右側運算元。 3 > 2 將返回 true
>= 檢查左側物件是否大於或等於右側運算元。 3 >= 2 將返回 true

以下程式碼片段顯示瞭如何使用各種運算子。

class Example { 
   static void main(String[] args) { 
      def x = 5;
      def y = 10;
      def z = 8;
		
      if(x == y) { 
         println("x is equal to y"); 
      } else 
         println("x is not equal to y"); 
			
      if(z != y) { 
         println("z is not equal to y"); 
      } else 
         println("z is equal to y"); 
				
      if(z != y) { 
         println("z is not equal to y"); 
      } else 
         println("z is equal to y"); 
					
      if(z<y) { 
         println("z is less than y"); 
      } else 
         println("z is greater than y"); 
						
      if(x<=y) { 
         println("x is less than y"); 
      } else 
         println("x is greater than y"); 
			
      if(x>y) { 
         println("x is greater than y"); 
      } else 
         println("x is less than y"); 
			
      if(x>=y) { 
         println("x is greater or equal to y"); 
      } else 
         println("x is less than y"); 
   } 
} 

當我們執行上述程式時,我們將得到以下結果。可以看出,結果與上述運算子描述的預期一致。

x is not equal to y 
z is not equal to y 
z is not equal to y 
z is less than y
x is less than y 
x is less than y 
x is less than y 
groovy_operators.htm
廣告

© . All rights reserved.