Java do while/while/for循环语句的使用【全网最详攻略】附练习题加以巩固(质数,多个数之和,水仙花数,一个数的阶乘)

在Java语言中,经常使用循环语句

first:do-while循环语句至少运行一次

 与while区别 循环条件必须满足才执行

换句话说,do-whlie语句先干完再说,比较直系,再进行while判断它够不够格,

而while语句要求严格,必须遵守条件

再说说while语句的使用

例题:用while来实现任意输入一个数n的阶乘

package JAVA;


    import java.util.Scanner;

public class Main5 {
    public static void main(String[] args) {

        System.out.print("请输入数字:");

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int a =1;int b =1;
        while (a <=num) {
            b=b*a;
            a++;

        }


          System.out.println("该数字的阶乘为"+b);
    }

而do while循环语句通过例题展示

例题:从键盘上输入一个整数,判断是几位数

​
package JAVA;


    import java.util.Scanner;

public class Main5 {
    public static void main(String[] args) {

        System.out.print("请输入整数:");

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int c =0;
       do {
           num/=10;
          c++;



       }while (num!=0);


          System.out.println("你输入的数字是"+c+"位数");
    }



​

最后就是最容易的循环语句(仅个人观点,勿喷)

second:for语句

来展示!!!

for (初始化语句;条件判断语句;条件控制语句){

​ 循环语句体;

}

例题:计算2+4+6+…+100的值

package JAVA;


public class Main5 {
    public static void main(String[] args) {


        int c;
        for (c=2; c <= 100; c++){


            System.out.println("2+3+...+100的和为"+c);

        }
    }

再来两道题练练手  嘿嘿嘿~·~~

例1:打印出1~100内的所有质数

package JAVA;


import sun.management.jdp.JdpController;

import static java.lang.Math.sqrt;

public class Main5 {
    public static void main(String[] args) {

int sum =0;
        int c;

        for (c=1; c <=100; c++) {
            boolean flag =true;
            int j;
            for (j = 2; j <= Math.sqrt(c);j++)
               if (c % j == 0) {
                flag = false;
                break;
            }
                 if (flag){
                   sum++;
                   System.out.println(c+"为质数");
               }



        }
    }

例2:

请打印100~999所有的水仙花数。

提示:符合各位的立方和等于其自身的数就是水仙花数,例如153=1³+5³+3³

package JAVA;



public class Main6 {

    public static void main(String[] args) {
        int a;

        for (a = 100; a <= 1000; a++) {
        int g = a %10;
        int s = (a / 10) % 10;
        int q = a / 100;
        if (g * g * g + s * s * s + q * q * q == a)
            System.out.println(a);}
    }
    
    
    
}

谢谢各位大朋友,小朋友的观看

附一句很喜欢的话:你要找到你的激情!不断寻找,不要凑活!

拜拜!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值