JAVA基础4-----循环语句跳转控制语句

1.for与语句
/*
for语句
for(初试表达式;条件表达式;循环后的操作表达式) {
循环体;
}
*/

class Demo1_for {
	public static void main(String[] args) {
		int i,x,y,z;
		for(i=100 ; i <= 999;i++) {
			x = i / 100;
			y = (i % 100) / 10;
			z = (i % 100) % 10;
			if(i == x * x * x + y * y * y + z * z * z ) {
				System.out.println(i + "是水仙花数");
			}
		}
}
}

2.while语句
/*
while语句:
初始化语句;
while(判断条件语句) {
循环体语句;
控制条件语句;
}
*/

class Demo1_While {
	public static void main(String[] args) {
		int i = 100,x,y,z,count = 0;
		
		while(i < 1000) {
			x = i / 100;
			y = (i % 100) / 10;
			z = i % 10;
			if(i == x * x * x + y * y * y + z * z * z) {
				count++;
			}
			i++;
		}
		System.out.println("count = " + count);
	}
}

3.do … while语句
/*
do while循环:
初始化语句;
do {
循环体语句;
控制条件语句;
}while(判断条件语句);
*/

class Demo1_DoWhile {
	public static void main(String[] args) {
		int i = 1;
		do{
			System.out.println("i = " + i);
			i++;
		}
		while (i <= 10);
	}
}

4./*
while和dowhile的区别
*/

class Demo1_DoWhile {
	public static void main(String[] args) {
		int i = 11;
		do{
			System.out.println("i = " + i);
			i++;
		}
		while (i <= 10);
		System.out.println("..........................");
		while (i <= 10){
			System.out.println("i = " + i);
			i++;
		}
	}
}

5.for和while循环的小区别.
for语句执行完之后变量会被释放,不能继续使用.
while语句在执行完之后,初始化的变量还可以继续使用.
如果在循环结束之后仍然要继续使用控制循环的变量则用while语句,不再继续使用则使用for循环,因为变量在内存中消失,可以提高内存的使用的效率
主要看变量定义的作用域在那里.
6.System.out.println和System.out.print的区别,println在每次输出之后都会自动打的加上一个换行.而print没有.

class Demo1_Print {
	public static void main(String[] args) {
		int i,j;
		for(i = 1;i <= 4;i++) {
			for(j = 1;j <= 5;j++) {
				System.out.print("*");
			}
			System.out.print("\n");
		}
	}
}
class Demo1_Println {
	public static void main(String[] args) {
		int i,j;
		for(i = 1;i <= 4;i++) {
			for(j = 1;j <= 5;j++) {
				System.out.println("*");
			}
		}
	}
}

7./*
控制跳转语句
A.break
只能在switch和循环中使用
B.continue
只能在循环中使用
*/在这里插入图片描述

class Demo1_Break {
	public static void main(String[] args) {
		for(int i = 1;i <= 10;i++) {
			if(i == 8)
				break;   //跳出循环
				System.out.println("i = " + i);
		}
	}
}

在这里插入图片描述

class Demo1_Continue {
	public static void main(String[] args) {
		for(int i = 1;i <= 10;i++) {
			if(i == 8)
				continue;//终止本次循环,进行下次的循环
			System.out.println("i = " + i);
		}
		}
	}

/*return的作用
返回
它的作用不是结束循环的,而是结束方法的

return是结束方法
break是跳出循环
continue是终止本次循环继续下次循环
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值