Reference herein Hey passenger network Java combat
Java break
description
The use of Java break ends the current cycle .
topic
Use break to end the current loop and calculate the data of 1, 2, 3, 4, 5, but only the sum of the first 3 numbers is required.
Problem solving ideas
- Define the loop to execute 5 times, and the loop variable from 1 to 5 represents all data.
- Use if to judge , when the loop reaches 4, use break to end the loop.
- Output the final result.
Code implementation
public class BreakDemo01 {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
// 定义一个变量存储结果
int sum = 0;
// 运用循环计算
for(int i = 1; i <= 5; i++){
if(i == 4){
break;
}
sum += i;
}
// 打印结果
System.out.println("1+2+3 结果为:" + sum);
}
}
The running result is as shown in the figure below:
Here you can see that the loop ends when it is executed for the fourth time.