码迷,mamicode.com
首页 > 编程语言 > 详细

java---随机小结

时间:2018-08-23 22:15:17      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:一个   app   nbsp   name   public   gettime   calendar   tin   i++   

package text;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

//  Java随机
public class Demo {
    public static void first(String[] args) {
        Random rand = new Random();
        for (int i = 0; i < 5; i++) {
            //System.out.println(Math.random());//随机小数
            System.out.println(rand.nextInt(10));//随机0-9的整数
            System.out.println(rand.nextInt(10) + 1);//随机1-10的整数
            System.out.println(rand.nextInt(11) + 10);//随机10-20的整数
            System.out.println(rand.nextBoolean());//随机真假
            System.out.println(rand.nextDouble());//随机小数
        }
    }
//    随机日期
    public static void date(String[] args) {
        Random rand = new Random();
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        long start = c.getTime().getTime();
        System.out.println(sdf.format(c.getTime()));
        c.set(2000,1,1,0,0,0);
        long end = c.getTime().getTime();
        System.out.println(sdf.format(c.getTime()));
       // long time = Math.round(rand.nextDouble() * (end - start) + start);
       // c.setTimeInMillis(time);
        System.out.println(sdf.format(c.getTime()));
    }
//  随机取出一个字母
    public static void world(String[] args) {
        //string stringBuffer stringBuilder的区别
        StringBuffer str = new StringBuffer("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890");
        StringBuffer temp = new StringBuffer("");
        Random rand = new Random();
        for (int i = 0; i < 10; i++) {
            temp.append(str.charAt(rand.nextInt(str.length())));
        }
        System.out.println(temp.toString());

    }
// 随机取出三个姓名且不重复
    public static void main(String[] args) {
        String[] arr = new String[]{"李飞","王伟","关羽","刘备","张飞"};
        Random rand = new Random();
        StringBuffer temp = new StringBuffer("");
        int i = 3;
        while(i > 0) {
            String name =arr[rand.nextInt(arr.length)];
          if(temp.indexOf(name) == -1){
              temp.append(name+" ");
                 i--;
          }
        }
        System.out.println(temp.toString());
    }
}

 

java---随机小结

标签:一个   app   nbsp   name   public   gettime   calendar   tin   i++   

原文地址:https://www.cnblogs.com/zxwen/p/9526384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!