产生10个1-100的随机数,并放到一个数组中,最后存储到number.txt文件中

    4.产生10个1-100的随机数,并放到一个数组中
   (1)把数组中大于等于10的数字放到一个list集合中,并打印到控制台。
   (2)把数组中的数字放到当前文件夹的number.txt文件中


    解题思路:
      1,产生1-100的随机数,存储到数组中
      2,数组中 >=10 的数存到List集合中
      3,遍历输出集合List
      4,把数组元素存放到 number.txt

代码如下:

/*
    4.产生10个1-100的随机数,并放到一个数组中
	    (1)把数组中大于等于10的数字放到一个list集合中,并打印到控制台。
	    (2)把数组中的数字放到当前文件夹的number.txt文件中

    解题思路:
      1,产生1-100的随机数,存储到数组中
      2,数组中 >=10 的数存到List集合中
      3,遍历输出集合List
      4,把数组元素存放到 number.txt
	
 */
package HomeWork4;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Array_Number {
	public static void main(String[] args) {
		double[] doubleArr = new double[10];
		List<Double> list = new ArrayList<Double>();
		stroeRandomNumber(doubleArr);
		storeInList(list, doubleArr);
		System.out.println(list);
		System.out.println("=================");
		getListElement(list);
	}

	/*
	 * 遍历list集合,并将list中的元素一个一个放到number.txt中
	 */
	public static void getListElement(List<Double> list) {
		for (int i = 0; i < list.size(); i++) {
			double d = list.get(i);
			putInNumber(d);

			System.out.println(d);
		}
	}

	/*
	 * 把数组元素放到number.list中
	 */
	public static void putInNumber(double d) {
		String str = d + "";
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream("h:\\number.txt", true);
			fos.write(str.getBytes());
			fos.write('-');
		} catch (IOException ex) {
			ex.printStackTrace();
			System.out.println(ex);
			throw new RuntimeException("写入失败!");
		} finally {
			try {
				if (fos != null)
					fos.close();
			} catch (IOException ex) {
				System.out.println(ex);
				throw new RuntimeException("释放资源失败!");
			}
		}
	}

	/*
	 * 数组中 >=10 的数存到List集合中
	 */
	public static void storeInList(List<Double> list, double[] doubleArr) {
		for (double d : doubleArr) {
			if (d >= 10)
				list.add(d);
			System.out.println(d);
		}
	}

	/*
	 * 1,产生1-100的随机数,粗存到数组中
	 */
	public static void stroeRandomNumber(double[] doubleArr) {
		for (int i = 0; i < 10; i++) {
			Random rand = new Random();
			doubleArr[i] = 1 + rand.nextDouble() * 100;// 生成[1.0-100.0]之间的随机数
		}
	}
}



  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值