A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 14900 初级黑马   /  2014-2-24 16:14  /  904 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。

评分

参与人数 1技术分 +1 收起 理由
何伟超 + 1

查看全部评分

5 个回复

倒序浏览
可以利用set集合的不重复特点   先存入集合中
回复 使用道具 举报
用一个ArrayList存储1到100:
  1. public class Rand {
  2.         public static void main(String[] args) {
  3.                 int[] fill = new int[100];
  4.                 List<Integer> list = new ArrayList<Integer>();
  5.                 for(int i=1; i<=100; i++) {
  6.                         list.add(i);
  7.                 }
  8.   
  9.                 Random random = new Random();
  10.                         for(int i=0; i<fill.length; i++) {
  11.                                 fill[i] = list.remove(random.nextInt(list.size()));
  12.                         }
  13.   
  14.                 for(int i=0; i<fill.length; i++) {
  15.                         System.out.print(fill[i] + " ");
  16.                 }
  17.         }
  18. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
何伟超 + 1

查看全部评分

回复 使用道具 举报
1.创建数组
2 产生随机数
3产生的数先判断数组中是否包含(遍历数组元素看是否有数字和该随机数相等),不包含就放
回复 使用道具 举报
面试题?给你说一下思路吧,代码就不贴了,可以使用Random随机数,random接口或Math类的random方法都可以实现这种效果,然后如楼上所说存入Set集合,还要注意处理基本数据拆装箱的问题
回复 使用道具 举报
  1. public class   Test
  2. {
  3.         public static void main(String[] args) {
  4.                 int [] arr=fun();
  5.         }

  6.         private static int[] fun() {
  7.                 Set<Integer> set =
  8.                                 new HashSet<Integer>();
  9.                 while(set.size()<100){
  10.                         set.add((new Random().nextInt(100))+1);
  11.                 }
  12.                 int []arr=new int[100];
  13.                 int i=0;
  14.                 for(int x:set)
  15.                         arr[i++]=x;
  16.                 return arr;
  17.         }
  18. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
何伟超 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马