大数据-java基础-第04章 while和do-while循环结构练习

    技术2022-07-12  73

    1.缸子里能装50升水。现有15升。每次能挑5升。要挑几次才能挑满? 分析: 1.定一个变量 a 来存储每次挑的水 2. 定义一个变量 b 来显示挑水的次数 3.判断条件为挑满水为止

    public class Excericse05 { public static void main(String[] args) { int a =5 ; int b =1; while((a*b)+15 <=50) { b++; } System.out.print("要挑"+(b-1)+"次才能挑满"); } }

    2.输出100以内能被7整除的前5个数 分析: 1.定义一个变量i ,在100以内 2.判断是否可以被7整除 3.定义一个循环变量A ,来限制前5个数

    public class Excericse04 { public static void main(String []agrs) { int a =1; int i =0; while (i <=100 && a <=5) { if (i % 7 == 0) { System.out.print(i+","); a++; } i++; } } }

    3.使用do-while实现:输出摄氏温度与华氏温度的对照表,要求它从摄氏温度0度到250度,每隔20度为一项,对照表中的条目不超过10条。 转换关系:华氏温度 = 摄氏温度 * 9 / 5.0 + 32 分析: 1.定义变量a 显示摄氏度温度,并且以20度为一项 2.定义一个变量b 来存储华式温度 3.定义i 来限制每页的条数

    public class Excericise03 { public static void main(String[] args) { int a = 0; int i =0; double b =32; do { System.out.println(a+"摄氏度"+"--"+b+"华式温度"); a =a +20; b =a*9/5.0+32.0; }while(a <= 250 && i <= 10 ); } }

    4.输入一个整数(1~9),求该数的阶乘并输出 分析: 1.定义一个变量来接收键盘输入的数字 2.定义一个变量c,用来与输入的数字进行比较循环次数 3.由于阶乘,键盘接收的变量依次减少

    public class Excercise02 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); System.out.println("请输入一个在0-9的整数"); int a =sc.nextInt(); int b = 1; int c = 1; while( c <= a ) { b =b *a; a--; } System.out.println(b); } }

    5.求出10的N次方的值,N为用户输入的 分析: 1.键盘输入需要次方的值,定义变量接收需要次方值 2.定义一个变量power,用来储存最好的次方值 3.定义一个变量C,用来判断需要循环次数,来是power 的值多次相乘

    public class Exercise04 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); System.out.print("请输入您想要求的次方值"); int a = sc.nextInt(); double power= 1; int c=1; if(a >=0) { while (c <= a) { power = 10*power; c++; } System.out.print(power); } else { while(a < 0) { power =0.1*power; a++; } System.out.print(power); } } }

    6.猜数字游戏,要求猜一个介于1~10之间的数字,根据用户猜测的数与标准值进行对比,并给出提示,以便下次猜测能接近标准值,直到猜中为止 分析: 1.你必须先输入一个数字 Scanner sc = new Scannner(system.in); 2.判断这个数字是否在1-10之间if( a >= 1 && a <=10) 3. 定义一个标准值 int b = 3 4.判断 这个值与标准值之间的关系 当 a > b 输出 您输入的值过大,请继续输入新的值 ,再次判断 当 a < b 输出 您输入的值过小,请继续输入新的值,再次判断 当 a = b 输出 你真厉害!! 备注:输入值变量的位置不同就会出现死循环情况

    public class Demo03 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("开始猜数字游戏!!请输入一个数字(数字介于0-10)"); int a = 0; int b = 3; do { a = sc.nextInt(); if (a > b ) { System.out.println("您输入的值过大,请继续输入新的值"); }else if (a < b){ System.out.println("您输入的值过小,请继续输入新的值"); } } while(a != b ); System.out.println("你真厉害!!"); } }
    Processed: 0.017, SQL: 9