Detailed explanation of Java break statement
•
Java
Terminate a sequence of statements in a switch statement
Use the break statement to forcibly exit the loop directly
Example 1
import java.util.Scanner;
public class Test24
{
public static void main(String[] args)
{
Scanner input=new Scanner(system.in); //定义变量存储小明的回答
String answer=""; //一圈100米,1000米为10圈,即为循环的次数
for(int i=0;i<10;i++)
{
System.out.println("跑的是第"+(i+1)+"圈");
System.out.println("还能坚持吗?"); //获取小明的回答
answer=input.next(); //判断小明的回答是否为y?如果不是,则放弃,跳出循环
if(!answer.equals("y"))
{
System.out.println("放弃");
break;
}
// 循环之后的代码
System.out.println("加油!继续!");
}
}
}
跑的是第1圈 还能坚持吗? y 加油!继续! 跑的是第2圈 还能坚持吗? y 加油!继续! 跑的是第3圈 还能坚持吗? n 放弃
public class BreakDemo1
{
public static void main(String[] args)
{
//外循环,循环5次
for (int i=0;i<5;i++)
{
System.out.print("第"+(i+1)+"次循环:");
//内循环,设计为循环10次
for(int j=0;j<10;j++)
{
//判断j是否等于3,如果是,则终止循环
if(j==3)
{
break;
}
System.out.print("内循环的第"+(j+1)+"次循环\t");
}
System.out.println();
}
}
}
第1次循环:内循环的第1次循环 内循环的第2次循环 内循环的第3次循环 第2次循环:内循环的第1次循环 内循环的第2次循环 内循环的第3次循环 第3次循环:内循环的第1次循环 内循环的第2次循环 内循环的第3次循环 第4次循环:内循环的第1次循环 内循环的第2次循环 内循环的第3次循环 第5次循环:内循环的第1次循环 内循环的第2次循环 内循环的第3次循环
Example 2
public class Test25
{
public static void main(String[] args)
{
int score; //每门课的成绩
int sum=0; //成绩之和
boolean con=true; //记录录入的成绩是否合法
Scanner input=new Scanner(system.in);
System.out.println("请输入学生的姓名:");
String name=input.next(); //获取用户输入的姓名
for(int i=1;i<=6;i++)
{
System.out.println("请输入第"+i+"门课程的成绩:");
score=input.nextInt();//获取用户输入的成绩
if(score<0)
{ //判断用户输入的成绩是否为负数,如果为负数,终止循环
con=false;
break;
}
sum=sum+score; //累加求和
}
if(con)
{
System.out.println(name+"的总成绩为:"+sum);
}
else
{
System.out.println("抱歉,分数录入错误,请重新录入!");
}
}
}
请输入学生的姓名: zhangpu 请输入第1门课程的成绩: 100 请输入第2门课程的成绩: 75 请输入第3门课程的成绩: -8 抱歉,分数录入错误,请重新录入!
请输入学生的姓名: zhangpu 请输入第1门课程的成绩: 100 请输入第2门课程的成绩: 68 请输入第3门课程的成绩: 73 请输入第4门课程的成绩: 47 请输入第5门课程的成绩: 99 请输入第6门课程的成绩: 84 zhangpu的总成绩为:471
Use the break statement to realize the function of goto
break label;
public class GotoDemo
{
public static void main(String[] args)
{
label:for(int i=0;i<10;i++)
{
for(int j=0;j<8;j++)
{
System.out.println(j);
if(j%2!=0)
{
break label;
}
}
}
}
}
0 1
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
