淺析Java隨機數與定時器,淺析java隨機數

來源:互聯網
上載者:User

淺析Java隨機數與定時器,淺析java隨機數

產生90-100的重複的隨機數:

public class RandomTest {   public static void main(String[] args){  /*   * Math.random()方法預設double類型,所以需要強制轉換為int   */    int x=(int)(Math.random()*(100-90+1)+90); //(max-min+1)+min=min-max    System.out.println(x);   } }

產生90-100不重複的隨機數:

import java.util.HashSet;import java.util.Random;import java.util.Set;public class RandomTest {public static void main(String args[]){int max=100; //最大值int min=90; //最小值int count=max-min; //隨機數個數Random random = new Random();Set<Integer> set=new HashSet<>(); //hashset容器中只能儲存不重複的對象while(set.size()<count){ //hashset儲存的元素數目 int x = random.nextInt(max-min+1)+min; //產生隨機數 set.add(x); //把隨機數添加到hashset容器中}for(int i:set){ //foreach遍曆容器元素System.out.println(i);}}}

每一秒產生90-100的重複的隨機數:

import java.util.Random;import java.util.Timer;import java.util.TimerTask;public class RandomTest { void timer(){Timer timer = new Timer(); //建立定時對象timer.schedule(new TimerTask() {public void run() { //TimerTask實現 Runnable介面的run方法 Random random = new Random(); int x = random.nextInt(100-90+1)+90; //(max-min+1)+min=min至max// int x=random.nextInt(100)%(100-90+1) + 90; //同樣的效果 System.out.println(x);}},0,1000); //0表示無延遲,1000ms=1s}  public static void main(String[] args){  RandomTest ran=new RandomTest();  ran.timer(); //調用定時任務  } } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.