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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 刘文秀 中级黑马   /  2016-7-31 23:56  /  459 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
* 2.产生10个1-100的随机数,并放到一个数组中(要求随机数不能重复)
        (3)把数组中的数字放到当前文件夹的number.txt文件中
*/
public class Second_Random {
        public static void main(String[] args) throws IOException {
                FileOutputStream fos = new FileOutputStream("number_random.txt");
                Random radom = new Random();
                int[] arr = new int[100];
                for (int i = 0; i < arr.length;i++) {
                        int r = radom.nextInt(100);
//                        if(arr[i]!=(r+1))
                        arr[i] = r + 1;
                        fos.write((arr[i]+"   ").getBytes());
                       
                }
                System.out.println("Done!");
                fos.close();
               
        }

}

3 个回复

倒序浏览
public class Second_Random {
        public static void main(String[] args) throws IOException {
                FileOutputStream fos = new FileOutputStream("number_random.txt");
                Random random = new Random();
                int[] arr = new int[10];
                //记录数组中元素的个数
                int count = 0;
                //当元素小于10 循环
                while(count < 10){
                        //获得随机数
                        int num = random.nextInt(99)+1;
                        //当数组中不包含当前随机数的时候执行
                        if(!Arrays.toString(arr).contains(String.valueOf(num))){
                                //给元素赋值
                                arr[count] = num;
                                //元素个数加1
                                count++;
                        }
                }
               
                StringBuffer sb = new StringBuffer();
                //获得所有元素,并组成一个字符串
                for (int i : arr) {
                        sb.append(String.valueOf(i)+" ");
                }
                //将数据写入文件
                fos.write(sb.toString().getBytes());
                //关闭流
                fos.close();

评分

参与人数 1黑马币 +2 收起 理由
r1503882525 + 2 赞一个!

查看全部评分

回复 使用道具 举报
你要获取10个的话应该有个循环执行10次

点评

看岔了,前面你当没看见...你定义的数组应该只有10个数把  发表于 2016-8-1 01:03
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马