2、使用IO流完成指定要求

編程題目:

2.產生10個1-100的隨機數,並放到一個數組中,完成如下要求:

(1)把數組中大於等於10的數字放到一個list集合中,並打印到控制檯;

(2)把數組中小於10的數字放到一個map集合中,並打印到控制檯;

(3)把數組中的數字放到當前文件夾的number.txt文件中。

示例代碼:

package program.stream.exercise02;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 2.產生10個1-100的隨機數,並放到一個數組中 (集合IO)
 * (1)把數組中大於等於10的數字放到一個list集合中,並打印到控制檯。
 * (2)把數組中小於10的數字放到一個map集合中,並打印到控制檯。
 * (3)把數組中的數字放到當前文件夾的number.txt文件中
**/

public class ArrayWriter {
    public static void main(String[] args) {

        int[] arr = new int[10];
        List<Integer> list = new ArrayList<Integer>();
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();

        //產生10個1-100的隨機數,並放到一個數組中
        System.out.println("遍歷數組:");
        int k = 0;
        for(int i=0;i<arr.length;i++){
            arr[i] = (int) (Math.random()*100+1);
            System.out.print(arr[i]+" ");
            if(arr[i] >= 10){
                list.add(arr[i]);
            }else if(arr[i] < 10){
                map.put(k++, arr[i]);
            }
        }

        //(1)把數組中大於等於10的數字放到一個list集合中,並打印到控制檯
        System.out.println("\nList遍歷:");
        for(int n : list){
            System.out.print(n+" ");
        }

        //(2)把數組中小於10的數字放到一個map集合中,並打印到控制檯
        System.out.println("\nMap遍歷:");
        Set<Integer> keySet = map.keySet();
        for(int key : keySet){
            System.out.print(map.get(key)+" ");
        }

        //(3)把數組中的數字放到當前文件夾的number.txt文件中
        Writer writer = null;
        BufferedWriter bufferedWriter = null;

        try {
            writer = new FileWriter("D:\\number.txt");
            bufferedWriter = new BufferedWriter(writer);

            for(int i=0;i<arr.length;i++){
                bufferedWriter.write(arr[i]+" ");
            }
            System.out.println("\n寫入完成!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedWriter.close();
                writer.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

結果顯示:

這裏寫圖片描述
這裏寫圖片描述

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