java算法按指定數量讀取集合或數組中的值

java算法按指定數量讀取集合或數組中的值

學習記錄

前言:因項目需要寫的這個算法,可能代碼不像詩,不優雅,但總算達到需求了,請大家多多指點

代碼如下:

 @org.junit.Test
    public void test(){
        //指定每次輸出多少數量的數據
        int munber = 5;
        //存放任意數量的數據
        String brandIds[] = new String[177];
        for (int i = 0; i<177; i++){
            brandIds[i] = i+"";
        }
        List<String> stringList = new ArrayList<>();
        //向上取值獲得總循環數
        int result =(int) Math.floor(brandIds.length/munber);
        int count =0;
        int rs = 0;
        for (int j = 0; j< result+1;j++) {
            String str = "";
            rs = count;
            count += munber;
            for (int i = 0; i < brandIds.length; i++) {
                //當前j 循環次數不等於總循環次數時執行下方if
                if (j != result) {
                    if (i >= count) {
                        System.out.println("str:" + str.substring(0,str.length()-1));
                        stringList.add(str.substring(0,str.length()-1));
                        break;
                    }
                    if (i >= rs) {
                        str += brandIds[count - count + i] + ",";
                    }
                } else {//當前j循環次數等於總循環次數時進入else,因爲我們是向上取得總循環數,最後一次循環做特殊處理因爲數量可能達不到我們指定的輸出數量,從而導致異常
                    if (i >= result * munber) {
                        str += brandIds[count - count + i] + ",";
                        if (i==brandIds.length-1){
                            stringList.add(str.substring(0,str.length()-1));
                            System.out.println("str2:"+str.substring(0,str.length()-1));
                        }
                    }
                }
            }
        }
    }

效果如下:
在這裏插入圖片描述在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章