JAVA基础-循环控制综合练习

获取随机数

在这里插入图片描述

小练习

1.猜数字小游戏

程序自动生成一个1-100之间的随机数字,使用程序实现猜出这个数字是多少?

    public static void main(String[] args) {
        Random r=new Random();
        int number=r.nextInt(10)+1;//1~10
        System.out.println("请猜数字");
        Scanner sc=new Scanner(System.in);
        int ans=sc.nextInt();
        while(true) {
            if (ans < number) {
                System.out.println("猜小了,请重新猜");
                ans = sc.nextInt();
                continue;
            } else if (ans > number) {
                System.out.println("猜大了,请重新猜");
                ans = sc.nextInt();
                continue;
            } else {
                System.out.println("猜中了");
                break;

            }

        }
    }

2.求质数

从键盘中输入一个整数,判断是不是质数

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int number=sc.nextInt();
        int i;
        boolean flag=true;
        for (i=2;i<=Math.sqrt(number);i++){
            if(number%i==0)
            {
                flag=false;
                break;

            }
            else continue;
        }
        if(flag)
            System.out.println(number+"是质数");
        else System.out.println(number+"不是质数");

    }

3.求平凡根

用循环求平方根

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int number=sc.nextInt();
        int i;
        for (i=1;i<number;i++){
            if(i*i<=number)
                continue;
            else break;
        }

        System.out.println(i-1);
    }

4.逢7过

包含7或者7的倍数,1-100

(7的倍数/个位是7/十位是7)

    public static void main(String[] args) {
        for (int i=1;i<=100;i++){
            if((i%7==0)||(i%10==7)||(i/10==7)){
                System.out.println("过");
                continue;
            }
            else System.out.println(i);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值