java中while与do-while的选择与应用

import java.util.Scanner;


public class Text3 {

	public static void main(String[] args) {
		Scanner in =new Scanner(System.in);
		int count = 0;
		int number = in.nextInt();
		do{
			number/=10;
			count++;
		}while(number>0);
		System.out.println(count);
	}

}

上述代码的作用是判断一个正整数是几位,使用的是do-while循环!while循环与do-while循环的区别主要在于do-while循环不管条件成不成立都会做一次循环,而while有可能一次也不做。上述代码中,number=0是不满足条件的!但它依然是一位数,故应该进循环。所以使用do-while循环更合理一些。

import java.util.Scanner;


public class Text4 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int result = 0;
		int number = in.nextInt();
		int digit;
		while(number>0){
			digit=number%10;
			result=result*10+digit;
			number/=10;
		}
		System.out.println(result);
	}

}
上述代码是求正整数的逆序输出。
import java.util.Scanner;


public class Text5 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int count=0;
		int number = (int)(Math.random()*100+1);
		int a;
		do{
			a=in.nextInt();
			count++;
			if(a>number){
				System.out.println("你猜的数大了!");
			}
			else if(a<number){
				System.out.println("你猜的数小了!");
			}
			
		}while(a!=number);
		System.out.println("恭喜你猜对了!猜了"+count+"次");
	}

}
上述代码是一个猜数游戏,其中Math.random()会产生一个区间为[0,1)的随机数。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值