while和do—while循环语句

while循环语句

格式:

while(判断条件语句){

​ 循环体语句;

}

扩展格式:

初始化语句;

while(判断条件语句){

​ 循环体语句;

​ 控制条件语句;

}

实例一

猜字游戏

思路:

While循环:

  • 猜的数字:int num = 456;
  • 条件:int guess;
  • while(guess != num){
  • 猜数字;
  • guess < num;猜小了
  • guess > num;猜大了
  • guess == num;break;
  • }
  • 猜对了!
public class WhileDemo {
	public static void main(String[] args) {
		//int  num = 456;
		//随机产生  Math.random()------0.0-0.9999999...
		int  num = (int)(Math.random()*1000) + 1;
		//System.out.println("要猜的数字是" + num);
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入猜的数字:");
		int guess = sc.nextInt();
		
		while(guess != num){
			if(guess > num){
				System.out.println("猜大了");
			}else{
				System.out.println("猜小了");
			}
			System.out.println("继续猜!");
			guess = sc.nextInt();	
		}
		if(guess == num){
			System.out.println("恭喜你,猜对了");
		}
		sc.close();
	}
}

do-while循环语句

格式:

do{

循环体语句;

}while(判断条件语句);

实例一

猜字游戏

public class DoWhileDemo {
	public static void main(String[] args) {
		int num = (int)(Math.random()*1000) + 1;
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入要猜的数字");
		int guess = sc.nextInt();
		
		do{
			if(guess > num){
				System.out.println("猜大了");
			}else{
				System.out.println("猜小了");
			}
			System.out.println("继续猜!");
			guess = sc.nextInt();
		}while(guess != num);
		if(guess == num){
			System.out.println("猜对了");
		}
	}
}

break和continue的区别:

continue:使用循环结构中,用于结束本次循环继续下一次循环。

break:可以使用在switch结构和循环结构中,用于跳出当前结构。

案例

public class Test {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			if(i % 2 == 0){
				continue;
			}
			System.out.print(i);
		}
	}
}
public class Test {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			if(i == 2){
				break;
			}
			System.out.print(i);
		}
	}
}
  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值