JAVA隨即產生不重複的數

來源:互聯網
上載者:User

import java.util.ArrayList;<br />import java.util.List;<br />import java.util.Random;<br />public class UnSeqRandomNumber {<br /> private int min;<br /> private int max;<br /> public UnSeqRandomNumber() {<br /> this.min = 0;<br /> this.max = 10;<br /> }<br /> public UnSeqRandomNumber(int min, int max) {<br /> this();<br /> if (max > min) {<br /> this.min = min;<br /> this.max = max;<br /> } else<br /> System.out.println("max比min小,按預設的值產生UnrepeatRandomMumber對象!");<br /> }<br /> // 第一種方法:排除法.隨機產生數字,如果是新產生的數字則放到結果集中<br /> // 否則不採取行動<br /> public Integer[] getRandomA(int length) {<br /> if (length <= 0) {<br /> System.out.println("數字長度小");<br /> return new Integer[0];<br /> } else if (length > (this.max - this.min)) {<br /> System.out.println("結果清單長度達不到要求:" + length + "結果只能是:" + (this.max - this.min));<br /> length = this.max - this.min;<br /> }<br /> Random rand = new Random();<br /> List<Integer> list = new ArrayList<Integer>();<br /> while (list.size() < length) {<br /> Integer randnum = new Integer(this.min + rand.nextInt(this.max - this.min + 1));<br /> if (!list.contains(randnum)) {<br /> list.add(randnum);<br /> }<br /> }<br /> return (Integer[]) list.toArray(new Integer[0]);<br /> }<br /> public static void outputArray(Integer[] array) {<br /> if (array != null) {<br /> for (int i = 0; i < array.length; i++) {<br /> System.out.println(array[i] + " ");<br /> }<br /> }<br /> System.out.println();<br /> }<br /> public static void main(String[] args) {<br /> // TODO Auto-generated method stub<br /> UnSeqRandomNumber test = new UnSeqRandomNumber(5, 35);<br /> outputArray(test.getRandomA(100));<br /> }<br />}<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.