Groovy 学习之四:运算符和循环、条件语句

本文详细介绍了Groovy中的运算符,包括算术、关系、逻辑、位、赋值和范围运算符,并展示了它们的用法和预期结果。接着讲解了Groovy的循环结构,如while、for、for-in循环,以及循环控制语句break和continue。最后,文章阐述了条件语句,包括if、if/else、嵌套if和switch语句的使用和执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Groovy运算符

运算符是一个符号,通知编译器执行特定的数学或逻辑操作。

Groovy中有以下类型的运算符:

  • 算术运算符
  • 关系运算符
  • 逻辑运算符
  • 位运算符
  • 赋值运算符

1、算术运算符

Groovy语言支持正常的算术运算符任何语言。以下是在Groovy中可用的算术运算符:

运算符描述例子
+两个操作数的加法1 + 2 将得到 3
从第一个操作数中减去第二个操作数2 - 1 将得到 1
*两个操作数的乘法2 * 2 将得到 4
/分子除以分母3 / 2 将得到 1.5
%模数运算符和整数/浮点除法后的余数3%2 将得到 1
++用于将操作数的值增加1的增量运算符

int x = 5;

x++;

x 将得到 6

- -用于将操作数的值减1的增量运算符

int x = 5;

X - ;

x 将得到 4

 以下代码段显示了如何使用各种运算符。

class demo4 {
    static void main(String[] args) {
        // Initializing 3 variables
        def x = 5;
        def y = 10;
        def z = 8;

        //Performing addition of 2 operands
        println(x+y);

        //Subtracts second operand from the first
        println(x-y);

        //Multiplication of both operands
        println(x*y);

        //Division of numerator by denominator
        println(z/x);

        //Modulus Operator and remainder of after an integer/float division
        println(z%x);

        //Incremental operator
        println(x++);

        //Decrementing operator
        println(x--);
    }
}

当我们运行上面的程序,我们将得到以下结果。可以看出,结果如从上面所示的操作符的描述所预期的。

15 
-5 
50 
1.6 
3 
5 
6

2、关系运算符

关系运算符允许对象的比较。以下书在Groovy中可用的关系运算符。

运算符描述例子
==测试两个对象之间的等同性2 == 2将得到true
!=测试两个对象之间的差异3!= 2将得到true
<检查左对象是否小于正确的操作数。2 <  3将得到true
<=检查左对象是否小于或等于右操作数。2 <  3将得到true
>检查左对象是否大于右操作数。3 > 2将得到true
>=检查左对象是否大于或等于右操作数。3 = 2将得到true

 以下代码段显示了如何使用各种运算符。

class demo5 { 
   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 

3、逻辑运算符

逻辑运算符用于计算布尔表达式。以下是在Groovy中提供的逻辑运算符。

运算符描述例子
&&这是逻辑“和”运算符true && true 将得到 true
||这是逻辑“或”运算符true || true 将得到 true
!这是逻辑“非”运算符!false 将得到 true

 以下代码段显示了如何使用各种运算符。

class demo6 {
    static void main(String[] args) {
        boolean x = true;
        boolean y = false;
        boolean z = true;

        println(x&&y);
        println(x&&z);

        println(x||z);
        println(x||y);
        println(!x);
    }
}

当我们运行上面的程序,我们将得到以下结果。可以看出,结果如从上面所示的操作符的描述所预期的。

false 
true 
true 
true 
false

4、位运算符

Groovy中提供了四个位运算符。以下是在Groovy中可用的位运算符。

运算符描述
&这是按位“和”运算符
|这是按位“或”运算符
^这是按位“xor”或Exclusive或运算符
~这是按位取反运算符

这里是显示了这些运算符的真值表。

pqp & qp | qp  ^  q
00000
01011
11110
10011

以下代码段显示了如何使用各种运算符。

class demo7 {
    static void main(String[] args) {
        int a = 00111100;
        int b = 00001101;
        int x;

        println(Integer.toBinaryString(a&b));
        println(Integer.toBinaryString(a|b));
        println(Integer.toBinaryString(a^b));

        a=~a;
        println(Integer.toBinaryString(a));
    }
}

当我们运行上面的程序,我们将得到以下结果。可以看出,结果如从上面所示的操作符的描述所预期的。

1001000000
1001001001000001
1001000000000001
1001001001000000

5、赋值运算符

Groovy语言也提供了赋值操作符。以下是在Groovy提供的赋值运算符。

运算符描述例子
+=这向左操作数添加右操作数,并将结果分配给左操作数。

def A = 5

A + = 3

输出将为8

-=这从左操作数中减去右操作数,并将结果分配给左操作数

def A = 5

A- = 3

输出将为2

*=这将右操作数与左操作数相乘,并将结果分配给左操作数

def A = 5

A * = 3

输出将为15

/=这将左操作数与右操作数相除,并将结果分配给左操作数

def A = 6

A / = 3

输出将为2

%=这使用两个操作数来取模,并将结果分配给左操作数

def A = 5

A%= 3

输出将为2

 以下代码段显示了如何使用各种运算符。

class demo8 {
    static void main(String[] args) {
        int x = 5;

        println(x+=3);
        println(x-=3);
        println(x*=3);
        println(x/=3);
        println(x%=3);
    }
}

当我们运行上面的程序,我们将得到以下结果。可以看出,结果如从上面所示的操作符的描述所预期的。

8 
5 
15 
5 
2 

6、范围运算符

Groovy支持范围的概念,并在..符号的帮助下提供范围运算符的符号。下面给出了范围运算符的一个简单示例。

def range = 0..5 

这只是定义了一个简单的整数范围,存储到一个局部变量称为范围内的下限为0和上限为5。

以下代码段显示了如何使用各种运算符。

class Example { 
    static void main(String[] args) {
        def range = 5..10;
        println(range.toArray());
        println(range.get(2));
    }
}

当我们运行上面的程序,我们会得到以下结果 -

从println语句中,可以看到显示在range语句中定义的整个数字范围。

get语句用于从定义的范围中获取一个对象,它将索引值作为参数。

[5, 6, 7, 8, 9, 10] 
7

7、运算符优先级

下表按优先级顺序列出了所有Groovy运算符。

运算符名称
++ - + -预增/减,一元加,一元减
* / %乘法,除法,取模
+ -加法,减法
==!= <=>等于,不等于,比较
二进制/位运算符与
^二进制/位异或
|二进制/按位或
&&逻辑和
||逻辑或
= ** = * = / =%= + = - = << = >> = >>> = = ^ = | =各种赋值运算符

 二、Groovy循环

到目前为止,我们已经看到已经按顺序方式一个接一个执行的语句。此外,在Groovy中提供了语句来改变程序逻辑中的控制流。然后将它们分类为我们将详细看到的控制语句的流程。

循环语句

序号语句和描述
1while语句

while语句首先通过计算条件表达式(布尔值)来执行,如果结果为真,则执行while循环中的语句。

2for语句

for语句用于遍历一组值。

3for-in语句

for-in语句用于遍历一组值。

 循环控制语句

序号语句和描述
1break语句

break语句用于改变循环和switch语句内的控制流。

2continue语句

continue语句补充了break语句。它的使用仅限于while和for循环。

 1、while 语句

while语句的语法如下所示:

while(condition) { 
   statement #1 
   statement #2 
   ... 
}

通过首先计算条件表达式(布尔值)来执行 while 语句,如果结果为true,则执行while循环中的语句。从while语句中的条件的评估开始重复该过程 此循环继续,直到条件计算为false。当条件变为假时,循环终止。 然后程序逻辑继续紧跟在while语句之后的语句。下图显示了此循环的图解说明。

While Loop

下面是一个while循环语句的例子:

class Example {
   static void main(String[] args) {
      int count = 0;
		
      while(count<5) {
         println(count);
         count++;
      }
   }
}

在上面的例子中,我们首先将计数整数变量的值初始化为0.然后我们在while循环中的条件是我们计算表达式的条件是计数应该小于5。count小于5,我们将打印count的值,然后增加count的值。上面的代码的输出将是:

0 
1 
2 
3 
4

2、for 语句

for 语句用于遍历一组值。for 语句通常以以下方式使用。

for(variable declaration;expression;Increment) { 
   statement #1 
   statement #2 
   … 
}

经典的语句包括以下部分:

  • 变量声明:此步骤对整个循环只执行一次,用于声明将在循环中使用的任何变量。
  • 表达式:这将包含一个表达式,将为循环的每次迭代计算。
  • 增量部分将包含在 for 语句中声明的变量所需的逻辑。

下图显示了此循环的图解说明。

For Loop

下面是一个经典的语句的例子:

class Example { 
   static void main(String[] args) {
	
      for(int i = 0;i<5;i++) {
	     println(i);
      }
   }
}

在上面的例子中,我们在 for 循环中做三件事 -

  • 声明变量 i 并将 i 的值初始化为0
  • 设置 for 循环的条件表达式应该执行,直到i的值小于5。
  • 每次迭代将 i 的值增加1。

上面的代码的输出将是:

0 
1 
2 
3 
4

3、for-in 语句

for-in 语句用于遍历一组值。for-in 语句通常以以下方式使用。

for(variable in range) { 
   statement #1 
   statement #2 
   … 
}

下图显示了此循环的图解说明。

For In Loop

以下是for-in语句的示例:

class Example { 
   static void main(String[] args) { 
      int[] array = [0,1,2,3]; 
		
      for(int i in array) { 
         println(i); 
      } 
   } 
}

在上面的例子中,我们首先初始化一个具有0,1,2和3的4个值的整数数组。然后我们使用for循环语句首先定义一个变量i,然后遍历数组中的所有整数 并相应地打印值。上面的代码的输出将是:

0 
1 
2 
3

for-in 语句也可用于循环范围。以下示例说明如何完成此操作。

class Example {
   static void main(String[] args) {
	
      for(int i in 1..5) {
         println(i);
      }
   } 
} 

在上面的例子中,我们实际上循环了从1到5定义的范围,并打印该范围中的每个值。上面的代码的输出将是:

1 
2 
3 
4 
5

for-in 语句也可用于循环访问Map。以下示例说明如何完成此操作。

class Example {
   static void main(String[] args) {
      def employee = ["Ken" : 21, "John" : 25, "Sally" : 22];
		
      for(emp in employee) {
         println(emp);
      }
   }
}

在上面的例子中,我们实际上循环通过一个映射,它有一组定义的键值条目。上面的代码的输出将是:

Ken = 21 
John = 25 
Sally = 22 

4、Break 语句

break 语句用于更改loop和switch语句内的控制流。我们已经看到break语句与switch语句结合使用。break语句也可以与while和for语句一起使用。使用这些循环结构中的任何一个执行 break 语句会立即终止最内层的循环。

下图显示了 break 语句的图解说明。

Break statement

以下是break语句的示例:

class Example {
   static void main(String[] args) {
      int[] array = [0,1,2,3];
		
      for(int i in array) {
         println(i);
         if(i == 2)
         break;
      }
   } 
}

上面的代码的输出将是:

0 
1 
2

正如预期的,因为有一个条件,说如果 i 的值为2,那么从循环中断,这就是为什么不打印数组的最后一个元素为3。

5、Continue 语句

continue语句补充了break语句。它的使用局限于while和for循环。当执行continue语句时,控制立即传递到最近的封闭循环的测试条件,以确定循环是否应该继续。对于该特定循环迭代,循环体中的所有后续语句都将被忽略。

Continue Statement

以下是 continue 语句的示例:

class Example {
   static void main(String[] args) {
      int[] array = [0,1,2,3];
		
      for(int i in array) {
         println(i);
         if(i == 2)
         continue;
      }
   }
}

上面的代码的输出将是:

0 
1 
2 
3

三、Groovy 条件语句

条件声明需要程序指定一个或者多个条件进行判断,如果条件被确定为真,则要执行一个或多个语句;如果条件被确定为假,则要执行其他语句。

序号语句和描述
1if 语句

这个语句的一般工作是首先在if语句中计算一个条件。如果条件为真,它然后执行语句。

2if / else 语句

这个语句的一般工作是首先在if语句中计算一个条件。如果条件为真,则其后执行语句,并在else条件之前停止并退出循环。如果条件为假,则执行else语句块中的语句,然后退出循环。

3嵌套 if 语句

i有时需要有多个if语句嵌入在彼此内部。

4Switch 语句

有时,嵌套的if-else语句是如此常见,并且经常使用,因此设计了一个更容易的语句,称为switch语句。

5嵌套 Switch 语句

switch也可以多层嵌套。

1、if 语句

第一个决策语句是 if 语句。这种说法的一般形式是:

if(condition) { 
   statement #1 
   statement #2 
   ... 
}

 这个语句的一般工作是首先在 if 语句中评估一个条件。如果条件为真,它然后执行语句。下图显示了 if 语句的流程。

If Statement

下面是一个if 语句的例子:

class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 2 
		
      //Check for the boolean condition 
      if (a<100) { 
         //If the condition is true print the following statement 
         println("The value is less than 100"); 
      } 
   } 
}

 在上面的例子中,我们首先将一个变量初始化为值2.然后我们评估变量的值,然后决定是否应该执行 println 语句。上面的代码的输出将是:

The value is less than 100

2、if / else 语句

我们将看到的下一个决策语句是 if / else 语句。这种说法的一般形式是:

if(condition) { 
   statement #1 
   statement #2 
   ... 
} else{ 
   statement #3 
   statement #4  
}

 这个语句的一般工作是首先在 if 语句中评估一个条件。如果条件为真,则其后执行语句,并在else条件之前停止并退出循环。如果条件为假,则执行else语句块中的语句,然后退出循环。下图显示了 if 语句的流程。

If Statements

下面是一个if / else语句的例子:

class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 2
		
      //Check for the boolean condition 
      if (a<100) { 
         //If the condition is true print the following statement 
         println("The value is less than 100"); 
      } else { 
         //If the condition is false print the following statement 
         println("The value is greater than 100"); 
      } 
   } 
}

 在上面的例子中,我们首先将一个变量初始化为值2.然后我们评估变量的值,然后决定应该执行哪个 println 语句。上面的代码的输出将是:

The value is less than 100.

3、嵌套 if 语句

有时需要有多个if语句嵌入在彼此内部。

这种说法的一般形式是:

if(condition) { 
   statement #1 
   statement #2 
   ... 
} else if(condition) { 
   statement #3 
   statement #4 
} else { 
   statement #5 
   statement #6 
}

 以下是嵌套if / else语句的示例:

class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 12 
		
      //Check for the boolean condition 
      if (a>100) {
         //If the condition is true print the following statement 
         println("The value is less than 100"); 
      } else 
         // Check if the value of a is greater than 5 
			
      if (a>5) { 
         //If the condition is true print the following statement 
         println("The value is greater than 5 and greater than 100"); 
      } else { 
         //If the condition is false print the following statement 
         println("The value of a is less than 5"); 
      }  
   } 
}

 在上面的例子中,我们首先将一个变量初始化为值12.在第一个 if 语句中,我们看到 a 的值是否大于100。如果没有,那么我们进入第二个for循环,看看 a 的值是否大于5或小于5.上面的代码的输出将是:

The value is greater than 5 and greater than 100

4、Switch 语句

有时,嵌套的if-else语句是如此常见,并且经常使用,以便设计一个更容易的语句,称为 switch 语句。

switch(expression) { 
   case expression #1: 
   statement #1 
   ... 
   case expression #2: 
   statement #2 
   ... 
   case expression #N: 
   statement #N 
   ... 
   default:
   statement #Default 
   ... 
} 

本声明的一般工作如下:

  • 要评估的表达式放在switch语句中。
  • 将有多个case表达式被定义以基于表达式的计算来决定应该执行哪一组语句。
  • 在结尾处的语句的每个案例段中添加一个 break 语句。这是为了确保在执行相关语句集时立即退出循环。
  • 还有一个默认case 语句,如果没有任何前面的情况表达式求值为true,则执行。

下图显示了 switch-case 语句的流程。

Switch Statements

以下是switch语句的示例:

class Example { 
   static void main(String[] args) { 
      //initializing a local variable 
      int a = 2
		
      //Evaluating the expression value 
      switch(a) {            
         //There is case statement defined for 4 cases 
         // Each case statement section has a break condition to exit the loop 
			
         case 1: 
            println("The value of a is One"); 
            break; 
         case 2: 
            println("The value of a is Two"); 
            break; 
         case 3: 
            println("The value of a is Three"); 
            break; 
         case 4: 
            println("The value of a is Four"); 
            break; 
         default: 
            println("The value is unknown"); 
            break; 
      }
   }
}

在上面的例子中,我们首先将一个变量初始化为值2,然后我们有一个switch语句,它计算变量a的值。 基于变量的值,它将执行语句的相关案例集。上面的代码的输出将是:

The value of a is Two

5、嵌套 Switch 语句

它也可以有一个嵌套的 switch 语句。语句的一般形式如下所示:

switch(expression) { 
   case expression #1: 
   statement #1 
   ... 
   case expression #2: 
   statement #2
   ... 
   case expression #N: 
   statement #N 
   ... 
   default: 
   statement #Default 
   ... 
}

下面是嵌套switch语句的一个示例:

class Example { 
   static void main(String[] args) { 
      //Initializing 2 variables i and j 
      int i = 0; 
      int j = 1; 
		
      // First evaluating the value of variable i 
      switch(i) { 
         case 0: 
            // Next evaluating the value of variable j 
            switch(j) { 
               case 0: 
                  println("i is 0, j is 0"); 
                  break; 
               case 1: 
                  println("i is 0, j is 1"); 
                  break; 
               
               // The default condition for the inner switch statement 
               default: 
               println("nested default case!!"); 
            } 
         break; 
			
         // The default condition for the outer switch statement 
         default: 
            println("No matching case found!!"); 
      }
   }
}

在上面的例子中,我们首先将a的变量初始化为a的值为2.然后我们有一个 switch 语句,它计算变量 a 的值。基于变量的值,它将执行语句的相关案例集。上面的代码的输出将是:

i is 0, j is 1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值