(JAVA) Character buffer stream to realize the caller

1. Caller requirements

Goal: Realize a name register, that is, randomly select a name from a file and output it.

2. Implementation steps

1). Create a character buffer stream object
2). Create an ArrayList collection object
3). Call the method of the character buffer stream object to read data and store it in the ArrayList object
4). Release resources
5). Use Random to generate random numbers in the range [0,ArrayList.size]
6). Use random number as index to get data in ArrayList

3. Implementation code


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class CallNameDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //1.创建字符缓冲流对象
        BufferedReader br = new BufferedReader(new FileReader("day18/src/names.txt"));
        //2.创建ArrayList集合对象
        ArrayList<String> arr = new ArrayList<>();
        //3.调用字符缓冲流对象的方法读取数据并存放到ArrayList对象中
        String line;
        while ((line=br.readLine())!=null){
    
    
            arr.add(line);
        }
        //4.释放资源
        br.close();
        //5.使用Random产生随机数,范围在[0,ArrayList.size]
        Random random = new Random();
        int index = random.nextInt(arr.size());
        //6.将随机数作为索引,获取ArrayList中的数据
        System.out.println("幸运的同学是:"+arr.get(index));
        
    }
}

4. Results display

Look at the contents of the names folder
Insert picture description here
first : then look at the results of the first run of the program: the results of the
Insert picture description here
second run:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45727931/article/details/108434274