Java-第四章 特殊结构与控制

不了解这里是否有结构体这样的特殊结构,但是for while循环和if判断 分支语句应该是素有语言必备的,可能就是写法稍微不同

所以就稍微提一下就好~ 与c和c#是一样的 不同于python和matlab。例子如下

public class Test {
   public static void main(String args[]) {
      int x = 3;
       
      //while循环
      while( x > 0 ) {
         System.out.print("value of x : " + x + "\n" );
         x--;
      }
	   
      //for循环
	  for(int j=3;j>0;j--)
	  {
	     System.out.print("value of j : " + j + "\n" );
	  }
	  
      //case分支
	  int k = 3;
	  switch(k)
	  {
		  case 1:System.out.print("value of k : " + k + "\n" );break;
		  case 2:System.out.print("value of k : " + k + "\n" );break;
	      case 3:System.out.print("value of k : " + k + "\n" );break;
	  }
	  
       
      //do-while循环
	  do
	  {
		 System.out.print("value of k : " + k + "\n" );
		 k--;
	  }while(k>0);
   }
}

java增强版本的for循环

在python中 c#等,可以使用集合的元素作为循环的元素,而不是必须是顺序的数字,例子如下:

public class Test {
   public static void main(String args[]) {
       
      String[] animal={"dog","cat","pig"};
      //采用 for(类型 变量名:集合名) 的方式遍历集合所有元素
      for(String ani:animal)
      {
         System.out.print(ani+"\n");
      }
      
      //普通采用下标的方式
      for(int i=0;i<3;i++)
      {
         System.out.print(animal[i]+"\n");
      }

   }
}

If判断语句

老规矩 可以多种情况 可以多层嵌套

public class Test {
   public static void main(String args[]) {
	   int score=92;
	   
	   if(score>80)
	   {
		   if(score>90)
		   {
		   System.out.print("优秀");
		   }
		   else
		   {
		   System.out.print("良好");
		   }
	   }
	   else if(score>60)
	   {
	   System.out.print("及格");
	   }
	   else
	   {
	   System.out.print("不及格");
	   }
   }
}

那么剩余的两个关键字 break continue也不用多数 这个没有变化的余地

扫描二维码关注公众号,回复: 6039972 查看本文章

break 跳出当前层循环 那么想要跳出两层循环,我一般使用一个flag

continue 继续当前循环体的下一次

猜你喜欢

转载自blog.csdn.net/iamsongyu/article/details/89630664
今日推荐