JAVA程序练习——BIO流实现读取五千个随机数并求最值和平均值

1.实现读取随机数需要使用Random工具,使用Current比new更简便
   ThreadLocalRandom r=ThreadLocalRandom.current();//等于new出一个random
                int[]arr=new int[5000];
                for(int i=0; i<arr.length; i++){
                    arr[i]=r.nextInt( 9999)+1;//0-9999改1-10000
2.求最大值,最小值和平均值的算法实现
 int max=Integer.MIN_VALUE;//求最大值
                    int min=Integer.MAX_VALUE;//求最小值
                    int sum=0;//求平均值
                    int count=0;
                    while(true){
                        try{
                            int kk=dis.readInt();
                            if (kk>max)
                                max=kk;
                            if (kk<min)
                                min=kk;
                            sum+=kk;//求和求平均
                            count++;
                    double res = 1. * sum / count;
3.输入输出流代码实现,写入a1.data
import java.io.*;
import java.util.concurrent.ThreadLocalRandom;
public class count {
    public static void main(String[] args)throws Exception{
                    ThreadLocalRandom r=ThreadLocalRandom.current();//等于new出一个random
                int[]arr=new int[5000];
                for(int i=0; i<arr.length; i++){
                    arr[i]=r.nextInt( 9999)+1;//0-9999改1-10000
        }
                try(
                        DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("a1.data")))
                        ) {
                    for (int tmp : arr)
                        dos.writeInt(tmp);
                }
                try (
                        DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream("a1.data")))
                        ) {
                    int max=Integer.MIN_VALUE;//求最大值
                    int min=Integer.MAX_VALUE;//求最小值
                    int sum=0;//求平均值
                    int count=0;
                    while(true){
                        try{
                            int kk=dis.readInt();
                            if (kk>max)
                                max=kk;
                            if (kk<min)
                                min=kk;
                            sum+=kk;//求和求平均
                            count++;
                        }catch (EOFException e){
                            break;
                        }
                    }
                    double res = 1. * sum / count;
                    System.out.printf("最大值为%d,最小值为%d,平均值为%f",max,min,res);
                }
    }
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值