Basic Java Learning: Controlling Execution Processes

Keywords: less Java

I. if-else

if(a > b){
	System.out.println("a greater than b");
}else if(a == b){
	System.out.println("a Be equal to b");
}else{
	System.out.println("a less than b");
}

II. while and do-while

  • while

     while(a < 10){
     	System.out.println("I'm smaller than 10.");
     }
    
  • do-while

     do{
     	System.out.println("Am I younger than 10?");
     }while(a < 10);
    

The difference between do-while and do-while is that do-while is executed first and then judged whether or not it meets the conditions.

for and foreach

  • for

     for(int i=0;i<10;i++){
     	System.out.println(i);
     }
    
  • Comma operator in for

     for(int i=0,j=0;i<10;i++,j=i*2){
     	System.out.println("i="+i+",j="+j);
     }
    
  • foreach

     Random rand = new Random(5);
     float[] f = new float[10];
     for(int i=0;i<10;i++){
     	f[i] = rand.nextFloat();
     }
     for(float x:f){
     	System.out.println(x);
     }
    

4. return, break, continue

  • Return causes the current method to exit or return that value (if the method has a return value)

     public void getTest(int a,int b){
     	if(a>b){
     		System.out.println("......");
     	}else{
     		return;
     	}
     }
     
     public int getTest(int a,int b){
     	if(a>b){
     		System.out.println("......");
     		return a;
     	}else{
     		return b;
     	}
     }
    
  • break is used to forcibly exit the current loop without executing the remaining statements in the current loop
    break stops the second for loop

      public static void getInt(){
     		for(int i=0;i<4;i++){
     			System.out.println("i="+i);
     			for(int j=0;j<2;j++){
     				System.out.println("i="+i+",j="+j);
     				if(i==2){
     					break;
     				}
     			}
     		}
     	}
    

    How to make break stop the outer for loop directly? In java, tags are used, as follows: ab: Tags

     public static void getInt(){
      	ab:
     	for(int i=0;i<4;i++){
     		System.out.println("i="+i);
     		for(int j=0;j<2;j++){
     			System.out.println("i="+i+",j="+j);
     			if(i==2){
     				break ab;
     			}
     		}
     	}
     }
    
  • continue is used to stop executing the current iteration, return to the starting point of the loop, and start the next iteration

Posted by wrongmove18 on Tue, 30 Jul 2019 21:44:43 -0700