思路:
/**
* 定义0-9的数组
* 定义变量保存数组的最后一位数的位置
* 定义变量保存最后的结果
* 通过传递过来的参数 进行遍历几次
* 定义变量保存随机出来的下标
* 定义变量保存随机出来的数 方便后面的交换
* 记录最后的结果
* 每次循环完更改数组最后的下标
* 在循环体外定义一个变量默认值为0,并保存通过Math.log10(数字变量) + 1; 获取的数字长度
* 再循环体外判断数字的长度,如果不等于四 在重新获取一个随机数,加到原来的数字后面
*/
代码:
package com.czxy;
import java.util.Random;
public class day05_03 {
static Random random = new Random();
public static void main(String[] args) {
for(int i = 0; i < 100; i++){
System.out.println(getRandomNumber(4));
}
}
public static long getRandomNumber(int len){
int[] arr = {0,1,2,3,4,5,6,7,8,9};
int last = arr.length - 1;
int retuls = 0;
int count = 0;
for(int i = 0; i < len; i++){
int index = random.nextInt(last + 1);
int temp = arr[last];
arr[last] = arr[index];
arr[index] = temp;
retuls = retuls * 10 + arr[last];
count = (int) Math.log10(retuls) + 1;
last--;
}
if(count != len){
int n = random.nextInt(10);
retuls = retuls * 10 + n;
}
return retuls;
}
}