• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

随机指定范围内N个不重复的数

randomCommon()方法负责制作赋值随机指定范围内N个不重复的数;

chachong()方法负责查重,判断数组中是否存在重复的数;

public class zuoye9_23_2 {
    public static int[] randomCommon(int min,int max,int n)
    {
        int str[]=new int[n];
        int i=0,j;
        while(i<n){
            int num=(int)(Math.random()*(max-min+1))+min;//分配一个随机数
            for(j=0;j<n;j++) {
                if(num==str[j]) {
                    num=(int)(Math.random()*(max-min+1)+min);//重新分配一个随机数
                    j=-1;//j重置为0
                }
            }
            str[i]=num;
            i++;
        }
        return str;
    }
    public static void main(String[] args)
    {
        int[] str=randomCommon(90,100,11);
        for(int temp:str) {
            System.out.print(temp+" ");
        }
        chachong(str);
    }
    public static void chachong(int[] a)
    {
        for(int i=0;i<a.length;i++) {
            int count=-1;
            for(int j=0;j<a.length;j++) {
                if(a[i]==a[j]) {
                    count++;
                }
                if(count==1) {
                    System.out.println("\n查到重复的!!!"+a[i]);
                    break;
                }
            }
        }
        System.out.println("\n恭喜,数组中无重复的值");
    }
}

输出

 为了确保程序是否真正能行,范围需要小些,需要多运行几次,查看是否有重复值。

posted on 2022-04-12 20:02  王陈锋  阅读(35)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3