首页 > 代码库 > 生成随机数的4个实例
生成随机数的4个实例
1、随机生成10个0~100之间的随机数组成数组
import java.util.Random;
import java.util.Arrays;
public class TestRandom
{
public static void main(String[] args)
{
Random rand = new Random();
int[] arr = new int[10];
for(int i=0;i<arr.length;i++)
{
arr[i] = rand.nextInt(100);
}
System.out.println(Arrays.toString(arr));
}
}
2、随机生成10个A~Z之间的字符组成数组
import java.util.Random;
import java.util.Arrays;
public class TestRandomAZ
{
public static void main(String[] args)
{
Random ran = new Random();
char[] arr1 = new char[26];
char[] arr2 = new char[5];
for(int i=0;i<arr1.length;i++)
{
arr1[i] = (char)(i+‘A‘);
}
for(int i=0;i<arr2.length;i++)
{
int a = ran.nextInt(26);
arr2[i]=arr1[a];
}
System.out.print(Arrays.toString(arr2));
}
}
3、在0~99随机生成10个不重复的数组成数组
import java.util.Random;
import java.util.Arrays;
public class TestRandomAZ
{
public static void main(String[] args)
{
Random ran = new Random();
int[] arr1 = new int[10];
for(int i=0;i<arr1.length;i++)
{
arr1[i] = ran.nextInt(100);
for(int j=0;j<i;j++)
{
if(arr1[i]==arr1[j])
{
i--;
}
}
}
System.out.print(Arrays.toString(arr1));
}
}
4、将3中的数组从小到大排列
import java.util.Random;
import java.util.Arrays;
public class TestRandomAZ
{
public static void main(String[] args)
{
Random ran = new Random();
int[] arr1 = new int[10];
for(int i=0;i<arr1.length;i++)
{
arr1[i] = ran.nextInt(100);
for(int j=0;j<i;j++)
{
if(arr1[i]==arr1[j])
{
i--;
}
if(arr1[i]<arr1[j])
{
int temp =arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp ;
}
}
}
System.out.print(Arrays.toString(arr1));
}
}
生成随机数的4个实例