Java實現產生一個int數組,長度為100,並向其中隨機插入1-100,並且不能重復。


    public  static void main(String[] args){
        //創建一個int數組,長度為100,
        int n = 100;
        int[] arrayInt = new int[n];
        Random random = new Random();
        ArrayList myList = new ArrayList();
        while(myList.size() < 100){
            //隨機函數生成0-100的整數
            int num = random.nextInt(101);
            //myList不包含則添加元素 去重
            if(!myList.contains(num) && num >0){
                myList.add(num);
            }
        }
        myList.sort(null);
        System.out.println(myList.size() + ",");
        //myList數組值賦值給int數組
        for(int i=0;i<100;i++){
            arrayInt[i] = (int)myList.get(i);
            System.out.println(arrayInt[i] + ",");
        }
    }

 大家可以用Integer數組試試,代碼要少點:

//    ArrayList<Integer> myList = new ArrayList<Integer>();
//    Integer[] b = new Integer[myList.size()];//當泛型為Integer時,需要
//    arrayInt = (Integer[])myList.toArray(b);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM