java---随机小结
Posted 阿稳是小可爱
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java---随机小结相关的知识,希望对你有一定的参考价值。
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---随机小结的主要内容,如果未能解决你的问题,请参考以下文章
[Java复习02] 集合框架Collection - 面试题小结