首页 > 编程语言 >使用IO流写一个随机点名程序

使用IO流写一个随机点名程序

时间:2023-11-10 19:55:25浏览次数:41  
标签:点名 String java ArrayList IO new 流写 import name

前言

最近学习了关于IO流的一些知识点,但是应用还不够,所以今天做个简单案例:

随机创建名字导入文件中:


package ioandcollection;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Random;


public class example02 {
    public static void main(String[] args) throws IOException{
        ArrayList<String> names = new ArrayList<>();
        String[] surnames = {"张", "王", "李", "赵", "刘", "陈", "杨", "黄", "周", "吴"};
        String[] maleNames = {"伟", "强", "磊", "军", "勇", "杰", "峰", "浩", "敏", "飞"};
        String[] femaleNames = {"芳", "娜", "婷", "秀", "霞", "敏", "莉", "红", "萍", "玲"};

        Random random = new Random();
        for (int i = 0; i < 15; i++) {
            String surname = surnames[random.nextInt(surnames.length)];
            String name;
            if (random.nextBoolean()) { // 随机选择男女
                name = maleNames[random.nextInt(maleNames.length)];
            } else {
                name = femaleNames[random.nextInt(femaleNames.length)];
            }
            names.add(surname + name);
        }
        writeName(names);
    }
    public static void writeName(ArrayList<String> names) throws IOException {
        String target = "filemould//students.txt";
        System.out.println(names);
        BufferedWriter wb = new BufferedWriter(new FileWriter(target));
        for (String name : names) {
            wb.write(name);
            wb.newLine();
            wb.flush();
        }
        wb.close();
    }
}

将名字导出存储在集合中,然后随机点名:


package ioandcollection;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Random;

/*
* 需求:有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随机点名器。
思路:
① 把文件中的数据读取到到集合中
② 使用Random产生一个随机数,获得随机索引。
③ 通过随机索引获取随机姓名
* */
public class example01 {
    public static void main(String[] args) throws IOException {
        ArrayList<String> list = new ArrayList<>();
        String content = "filemould\\students.txt";
        readFileContent(content,list);
        //产生一个随机数,获得随机索引
        Random random = new Random();
        int randomIndex = random.nextInt(list.size());

        //获取随机数姓名
        String randomName = list.get(randomIndex);
        System.out.println("被点到的同学是:" + randomName);
    }

    private static void readFileContent(String content,ArrayList<String> list) throws IOException {
        BufferedReader br = null;
        //创建文件字节缓冲输入流对象
        br = new BufferedReader(new FileReader(content));

        //一次读取一个字符
        String name;
        while((name = br.readLine())!=null){
            list.add(name);
        }
        System.out.println(list);
        br.close();
    }
}

总结:

1、wb.newLIne()可以将光标移动到下一行

2、br.readLine()可以读取下一行的内容

标签:点名,String,java,ArrayList,IO,new,流写,import,name
From: https://www.cnblogs.com/new-one/p/17824908.html

相关文章

  • measures to mitigate marine pollution
    Reducemarinepollutionby limitingthewastematerial.Stopusingplastic-made materialtosavemarinelifeandourenvironment.Cleantheseabeaches.Beachescleaned,marinepollutioncanbereducedtosomeextent.Thefarmersshoulduse organicfarmi......
  • 关于asyncio.create_task异步并发执行的研究
    关于asyncio.create_task异步并发执行的研究#不在乎结果版本asyncdefdo_some_thing(a,b):time.sleep(3)print(f"{datetime.datetime.now()}handledo_some_thingwitha:{a}andb:{b}")returna+bclassTaskHandler(tornado.web.RequestHandler):......
  • Soil salinization improvement土壤盐渍化改良
    Soilsalinizationimprovement土壤盐渍化改良1.Chemicalimprovementmeasures化学改良措施Chemical improvement measures are the methods of improving saline soil by applying chemical amendments and mineral fertilizers. Commonly used chemical......
  • Chinese strategy for tackling water pollution
    "Watersavingpriority,spatialbalance,systemmanagement,twohandshairforce"principle,carryoutthe"safety,clean,health"policy,strengthenthesourcecontrol,waterasawhole,theriver,theriversandlakesofbasin,regio......
  • How to solve marine pollution in China?
    MeasurestopreventandcontrolmarinepollutioninChinaEstablishandimprovethemarinelegalsystemandmanagementsystem.Since1978,Chinahassuccessivelyformulatedaseriesofmarineandsea-relatedlawsandregulations,suchastheLawofthe......
  • axios的this指向问题
    letvue=newVue({ methods:{ testMethod:function(){ //第一个: axios({ method:"post", url:"CartServlet", }).then(response=>{ this.cartJson=response; }); //第二个: axios({ method:"po......
  • Alluxio读写流程
    1.背景在https://blog.51cto.com/u_15327484文章中,介绍了Alluxio的架构。本文基于此,介绍Alluxio文件读写流程。Alluxio读写流程几乎和HDFS一致,只是Worker多了一个从UFS读写的选项,本文会省略部分流程,只介绍重点。2.Alluxio写流程客户端向Alluxio写数据时,可以指定是否就Alluxio......
  • Collection使用
      ......
  • Redis Functions 介绍之二
    首先,让我们先回顾一下上一篇讲的在RedisFunctions中关于将key的名字作为参数和非key名字作为参数的区别,先看下面的例子。首先,我们先在一个Lua脚本文件mylib.lua中定义如下的库和函数。//--------------------mylib.lua文件开始-----------//#!luaname=myliblocalfunct......
  • A solution to land sailnization
    Biologicallyimprovedsaline-alkalilandisbarrenandsoilfertilityispoor.Therefore,intheprocessoftransformation,itisanimportantmeasuretoimprovesalinitybyplantingpaddyfields,plantingsaline-alkalitolerantcrops,andincreasingthe......