22 Do you know the difference between return, break and continue when learning Java from scratch?

Author : Sun Yuchang, nicknamed [ Brother Yiyi ], and [ Brother Yiyi ] is also me

Senior teaching researcher of Qianfeng Education, CSDN blog expert, Wanfan blogger, Alibaba Cloud expert blogger, high-quality Nuggets author

Supporting project information

https://github.com/SunLtd/LearnJava
https://gitee.com/sunyiyi/LearnJava

foreword

In the last article, Brother Yi introduced two loop structures, while and do-while, and summarized the differences between the two loops. In fact, in the process of using loops to perform repeated operations, there is another requirement: how to abort, or end a loop early? For example, we are outputting numbers within 10,000 in a loop. What should we do if we want to stop the loop operation early because a certain condition is triggered? So today I will explain to you how to return a result in java code, how to end and jump out of a loop.

----------------------------------------------- Foreplay is over Finished, the wonderful begins -------------------------------------------- -

The full text is about [ 2800] words, no nonsense, just pure dry goods that allow you to learn techniques and understand principles! This article contains rich cases and videos with pictures, so that you can better understand and use the technical concepts in the article, and can bring you enough enlightening thinking...

1. break

1. Function

The break keyword can be used in for, while, do-while, and switch statements to jump out of the entire statement block and end the execution of the current loop. In addition, we must pay special attention to that the break statement always jumps out of the loop at which it is located . When two for loops are nested, if the break statement is located in the inner for loop, it will only jump out of the inner for loop, but not the outer for loop.

2. Grammar

The usage of break is very simple, we have already used it when we learned switch before. Generally, write the following statement in a loop or switch statement:

break;

For example, when we use the for loop to calculate the sum accumulated from 1 to 100, inside the loop, we can use if to judge, and when i==50, use the break keyword to end the loop in advance. Therefore, break is often used in conjunction with if statements.

3. Case

3.1 Case 1

break will jump out of the current for loop. When the break is executed, the current entire for loop will end execution.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo01 {
	public static void main(String[] args) {
		//break关键字
		
		//需求:从1累加到100,找到累加到哪个数时,就使得sum和大于888
		// 定义变量保存总和
		int sum = 0;
		
		for (int i = 1; i <= 100; i++) {
			sum = sum + i;
			if (sum > 888) {
				System.out.println("累加到"+i+"时,sum和就大于888");
				// 结束当前循环
				break;
				//这里的语句执行不到,编译阶段就会报错
				//System.out.println("能执行吗??");
			}
			//这里的语句可以执行,当break跳出循环后,就不会再继续执行
			System.out.println("能执行吗??"+i); 
		}
	}
}

Everyone should pay attention, we cannot directly follow the break with other statements, otherwise "Unreachable code" will appear during the compilation phase, as shown in the following figure:

3.2 Case 2

Requirements: Output the input content, if you input "886", it will end the current chat.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * CSDN、掘金、知乎找我哦
​​​​​​​ * 千锋教育
 */
import java.util.Scanner;

public class Demo02 {
	public static void main(String[] args) {
		//break关键字
		Scanner sc = new Scanner(System.in);
		
		while(true){
		    String word = sc.next();
		    if(word.equals("886")){
		    	//跳出当前循环
		        break;
		    }            

            //输出内容
		    System.out.println(word);            
		}
	}
}

2. continue

1. Function

continue is applicable to various loop structures and cannot be used in other places. It is used to skip this loop and execute the next loop . break can jump out of the current loop, that is, the entire loop will not be executed. Unlike break, continue is to end this cycle ahead of time, but will continue to execute the next cycle. In a multi-layer nested loop, continue can also indicate which level of loop to skip through the label, and also only ends the loop it is in.

2. Grammar

The usage of continue is very simple, just use the following statement directly in the loop structure:

continue;

3. Case

3.1 Case 1

Requirements: Output all integers within 100 that are not multiples of 3. Use continue to end the current loop and continue to the next loop.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo03 {
	public static void main(String[] args) {
		//continue关键字
		
		//案例:输出100以内,所有不是3的倍数的整数
		for(int i = 1; i <= 100 ; i++){
		    if(i % 3 == 0){
		    	//结束本次循环,继续执行下次循环,并不会结束整个循环,直到完成整个循环
		        continue;
		    }        
		    System.out.println(i);            
		}
	}
}

3.2 Case 2

Requirements: Output the input content, if you input "886", it will end the current chat. If a sensitive word is entered, it will be displayed with "***" instead.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
import java.util.Scanner;

public class Demo04 {
	public static void main(String[] args) {
		//continue关键字
		
		//需求:将输入的内容进行输出,如果输入"886"就结束当前聊天。如果输入了敏感词汇,则用“***”替代显示
		Scanner sc = new Scanner(System.in);
		
		while(true){
		    String word = sc.next();
		    if(word.equals("886")){
		    	//跳出整个循环
		        break;
		    }            
		    
		    if(word.equals("WC")||word.equals("SB")){
		        System.out.println("***");
                //中止本次循环,继续下一次循环
		        continue;
		    }
		    System.out.println(word);            
		}
	}
}

4. Jump when multi-layer loop nesting

When multiple loops are nested, the inner loop can use variables from the outer loop. Every time the outer loop loops, the inner loop will execute all the times of the inner loop. break/continue will only control the current loop. When multiple loops are nested, in order to facilitate control, we can control the loop by setting a label.

4.1 Grammar

When multi-level loop nesting, the syntax structure with labels is as follows:

label1: { ……
    label2: { ……
        label3: { ……
            break label2;
        } 
    } 
}

When there are multiple layers of loop nesting, we can give each loop a label name, the name is arbitrary, as long as it conforms to the identifier naming rules in java. Then combine break or continue to end the current or current loop.

4.2 Case

Here is a case with labels in multi-layer loop nesting, for your reference as follows:

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo07 {
	public static void main(String[] args) {
		//多层循环嵌套
		//打印5行5列的矩形,用 * 表示
		label01:for(int i = 1 ; i <= 5 ;i++){ //控制行

		    label02:for(int j = 1 ; j <= 5 ; j++){//控制列
		        System.out.print(" * ");
		        //当执行到第3列时,提前跳出循环
		        if(j==3) {
		        	break label02;
		        	//continue label02;
		        }
		    }
		    
		    //进行换行
		    System.out.println();
		}
	}   
}

3. return

Regarding the return keyword, after a brief introduction by Brother Yi today , we will explain it in detail later when we learn Java's "methods"!

1. Function

return is not a keyword specifically used to end a loop, it can be used to end a method or loop. When a method executes to the return statement, the method will be terminated. Different from break and continue, return directly ends the entire method, no matter how many layers of loops this return is in.

2. Grammar

The basic syntax of the return keyword is as follows:

访问修饰符 返回值类型 方法名(参数...){
	//方法体
    //注意:这里返回值的类型必须与方法上声明的返回值类型一致!
    return 返回值;
}

3. Case

Because the usage of return is mainly related to the "method" in java, so Yige will briefly show you two basic cases here, and then we will study the method and the content of return in detail later.

3.1 Case 1

Returns a result of the type specified by the value in the method.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo05 {
	public static void main(String[] args) {
		// return关键字
		//调用定义的方法,并获取返回结果
		String result = sayHello();
		System.out.println("result="+result);
	}
	
	//定义一个带有String类型返回值的方法
	//访问修饰符 返回值类型 
	public static String sayHello() {
		//本方法中只能返回String类型
		return "Hello,壹壹哥!";
	}
}

3.2 Case 2

return can also be used in a loop to end the entire loop.

/**
 * @author 一一哥Sun
 * QQ:2312119590
 * CSDN、掘金、知乎找我哦
 * 千锋教育
 */
public class Demo06 {
	public static void main(String[] args) {
		// return关键字
		for (int i = 1; i <= 10; i++) {
			for (int j = 1; j <= 10; j++) {
				if (i + j == 10) {
					//结束整个循环的执行,无论循环的层次
					return;
				}
				
				System.out.println("i = " + i + ",j = " + j + ",i + j = " + (i + j));
			}
		}

		//这里执行不到
		System.out.println("循环之后的语句");
	}
}

------------------------------------------------------​​ ​​​​The feature film is over, here is an afterthought ------------------------------------- ---------

4. Conclusion

So far, Brother Yi has explained the three keywords return, break, and continue to everyone. Now do you know the usage and difference between them? Next, Brother Yi will give you a summary of these keywords.

1. The comparison between break and continue

1.1 Different features

  • The break statement can jump out of the current loop;
  • The break statement is usually used in conjunction with if, and the entire loop can be ended early when the condition is met;
  • The break statement always jumps out of the nearest loop;
  • The continue statement can end this loop early;
  • The continue statement can also cooperate with the if statement to end the loop early when the condition is met.

1.2 Different usage occasions

  • break can be used in switch structure and loop structure;
  • continue can only be used in loop structures.

1.3 different functions

  • The break statement is used to terminate a loop, and the program jumps to the next statement outside the loop block;
  • The continue statement is used to jump out of this loop and enter the next loop.

2. The comparison between continue, break and return

  • break : end the loop;
  • continue : Skip this cycle and continue to the next cycle;
  • return : end the entire method.

The above is the key content of today's summary, I hope you will be proficient in memorizing these features. If you find it difficult to study alone, you can join Yi Ge 's learning mutual aid group, and everyone can exchange and learn together.

5. Supporting video

If you are not used to reading technical articles, or do not have a good understanding of the technical concepts in the article, you can take a look at the video tutorials selected by Yige for you. The Java learning video accompanying this article is linked as follows:

bilibili html5 player

6. Homework for today

1. The first question

Use a while loop to print out all integers between 10 and 100 that are divisible by both 5 and 9.

Guess you like

Origin blog.csdn.net/syc000666/article/details/130236556