java 從List中隨機取出一個元素

package com.example.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AllController {

    public static void main(String[] args) {
        aa();
        bb();
        cc();
    }

    /**
     * string
     */
    public static void aa() {
        List<String> list = new ArrayList<>();
        list.add("乾飯");
        list.add("稀粥");
        list.add("炒菜");
        list.add("麪條");
        list.add("火鍋");
        list.add("冒菜");
        list.add("麻辣燙");
        list.add("燒烤");
        Random random = new Random();
        int n = random.nextInt(list.size());
        String aa = list.get(n);
        System.out.println(aa);
    }

    /**
     * integer
     */
    public static void bb() {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        list1.add(5);
        list1.add(6);
        list1.add(7);
        list1.add(8);
        Random random = new Random();
        int n = random.nextInt(list1.size());
        Integer bb = list1.get(n);
        System.out.println(bb);
    }

    /**
     * 產生0-99/1-100的隨機數
     */
    public static void cc(){
        Random random = new Random();
        int ran1 = random.nextInt(100);
        int ran2 = random.nextInt(100)+1;
        System.out.println(ran1);

    }
    
}

 

發佈了28 篇原創文章 · 獲贊 31 · 訪問量 8281
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章