各种数据类型的随机数生成器 -- Java

本文介绍了一个用于生成多种类型随机数据的Java类。该类提供了生成整数、浮点数、日期、字符串等不同数据类型的实用方法。每种方法都经过精心设计以确保生成的数据既随机又符合指定的范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


由于比较简单,直接看代码吧


public class RandomDataGenerator
{
	public static long getInteger(long minValue, long maxValue)
	{
		return (long)(Math.random() * (maxValue - minValue + 1)) + minValue;
	}

	public static String getDouble(int exponent, int precision)
	{
		StringBuilder sb = new StringBuilder();
		sb.append((Math.random() < 0.5 ? "+" : "-"));
		sb.append((int)(Math.random() * 10) + ".");
		precision = (int)(Math.random() * precision);
		for (int i = 0; i < precision; i++)
			sb.append((int)(Math.random() * 10));
		sb.append("e" + (Math.random() < 0.5 ? "+" : "-") + ((int)(Math.random() * (exponent + 1))));
		return sb.toString();
	}

	//a.b; .b; a.
	public static String getDecimal(int p, int s){
		StringBuilder sb = new StringBuilder(Math.random() < 0.5 ? "+" : "-");
		while (true)
		{
			int size1 = (int)(Math.random() * (p - s + 1));
			int size2 = (int)(Math.random() * (s + 1));
			for (int i = 0; i < size1; i++)
				sb.append((int)(Math.random() * 10));
			sb.append(".");
			for (int i = 0; i < size2; i++)
				sb.append((int)(Math.random() * 10));
			if (!sb.toString().matches("[+-.]+"))
				break;
			sb.delete(0, sb.length());
			sb.append(Math.random() < 0.5 ? "+" : "-");
		}
		return sb.toString();
	}

	public static long getDate(long beginDateMillisecond, long endDateMillisecond)
	{
		return (long)(Math.random() * (endDateMillisecond - beginDateMillisecond + 1)
				+ beginDateMillisecond);
	}

	private static char[] chars = 
			"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

	public static String getString(int length)
	{
		int randomLength = (int)(Math.random() * (length + 1));
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < randomLength; i++)
			sb.append(chars[(int)(Math.random() * 62)]);
		return sb.toString();
	}

	public static char getChar()
	{
		return chars[(int)(Math.random() * 62)];
	}

	public static boolean getBoolean()
	{
		return Math.random() < 0.5 ? true : false;
	}
	
	public static double getNumeric(double minValue, double maxValue)
	{
		return Math.random() * (maxValue - minValue + 1) + minValue;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值