今天主要内容是Java中的循环结构语句和跳转控制语句;
for循环语句:
格式:
for(初始化语句;判断表达式;步长语句){
循环语句体;
}
执行流程:
1 进入for循环,初始化语句给变量赋值;
2判断表达式是否成立,成立则执行循环语句体;
3控制变量与具体对变量进行递增;
4再次判断表达式是否成立,成立则执行循环语句体;
5依次执行,直到表达式不成立为止,for循环结束;
例:
//在控制台输出500次"Hellowold"
class Demo{
public static void main(String[] args){
for(int x = 1; x<=500;x++){
System.out.println("Helloworld");
}
}
}
求和思想和阶乘思想,
求和思想:
第一个加数:前两个数据之和的结果;
第二个加数:从0开始一直到10;
//求1到10之间的和
class Demo{
public static void main(String[] args){
int sun = 0;
for(int x=1;x<=10;x++{
sun += x;
}
System.out.println("1到10之间的和为:"+sun);
}
}
阶乘思想:
n! = n*(n-1) …321 ;
n! = n(n-1)!;
//求10的阶乘
class Demo{
public static void main(String[] args){
int sun = 1;
for(int x=1;x<=10;x++){
sun *= x ;
}
System.out.println("10的阶乘为:"+sun);
}
}
水仙花
0)定义一个统计次数的变量
int count = 0 ;
1)水仙花:就是三位数;
特点: 每个位的数据的立方和是当前数据本身
2)获取每个位上的数据
int ge= x % 10 ;
int shi = x /10 % 10 ;
int bai = x /10 /10 % 10 ;
3)每个位上的数据满足条件
x == gegege+shishishi+baibaibai
4)满足上面的条件 :count++
5)for循环的输出count值
class Demo{
public static void main(String[] args){
//定义统计变量
int count = 0 ;
for(int x = 100 ; x < 1000; x ++){
//获取每个位上的数据;
int ge= x % 10 ;
int shi = x /10 % 10 ;
int bai = x /10 /10 % 10 ;
//满足条件
if(x==(ge*ge*ge+shi*shi*shi+bai*bai*bai)){
System.out.println("水仙花为:"+x) ;
count++ ;
}
}
System.out.println("所有的水仙花数共有:"+count+"个");
}
}
while循环结构语句
while循环的基本格式:
while(条件表达式){
循环体语句;
控制体语句/步长语句;
}
while循环的扩展格式:(常用)
初始化语句;
while(条件表达式){
循环体语句;
控制体语句/步长语句;
}
class WhileDemo{
public static void main(String[] args){
int x = 1 ;
while(x<=10){
System.out.println("helloworld") ;
//控制体语句
x ++ ;
}
}
}
for循环和while循环的区别?
1)在开发中,如果明确循环的次数,使用for循环 ;不明确循环次数,使用while循环
2)从内存角度考虑:
for循环结束之后,{}中的变量值会及时从内存中释放掉,不会消耗内存间!
while循环结束,还可以去访问变量值,不会立即从内存中释放掉,等待GC垃圾回收器,空闲时候回收!
3)开发中优先使用for循环,其次是while循环
注意事项:
在使用循环语句的时候,时刻观察变量的变化,尤其使用whil循环的时候,控制体语句经常会被忘掉书写,导致死循环;
do-while的扩展格式
初始化语句;
do{
循环体语句;
控制体语句/步长语句;
}while(条件表达式) ;
do-while循环,for循环,while循环的区别:
循环体至少执行一次;开发中,优先去使用for,如果不明确循环次数,使用while循环,最后考虑使用do-while循环;
循环嵌套:
for循环嵌套
for(初始化语句;条件表达式;控制台语句){
for(初始化语句;条件表达式;控制台语句){
}
}
class Demo{
public static void main(String[] args){
for(int x=1;x<=9;x++){
for(int y; y<=x;y++){
int z = x*y;
System.out.print(x+"*"+y+"="+z+"\t");
}
System.out.println();
}
}
}
Java中的转义字符
“\t” :制表符
“\n” :换行
“\r” :回车
跳转控制语句分为三种
break:中断,结束的意思
单独不能使用,只能switch语句或者循环语句(for,while…)中使用
continue: 表示结束当前循环,
立即进入下一次循环,不能单独使用,必须借助于循环语句中使用
return:要用来结束方法
需要带回给方法具体的结果,有return,说明方法有具体的返回结果
class Test7{
public static void main(String[] args){
for(int x=1;x<5;x++){
if(x==3){
break;
}
System.out.println(x);
}
System.out.println("--------------------");
for(int x=1;x<5;x++){
if(x==3){
continue ;
}
System.out.println(x);
}
System.out.println("--------------------");
for(int x=1;x<5;x++){
if(x==3){
return ;
}
System.out.println(x);
}
}
}