About Random random number class

5 does not generate the same random numbers into an array

  • Option One
public class RandomTest02 {
    public static void main(String[] args) {

        // 开辟数组空间
        int[] arr = new int[5];
        // 默认将数组中所有元素初始化为 0 
        for (int i = 0;i < arr.length; i++){
            arr[i] = -1;
        }
        // 创建 Random 对象
        Random r = new Random();
        //关键的 index
        int index = 0;
        
        w:while(index < arr.length){
            // 这里为了显示效果,将边界设置为 6,即数字取值范围为[0,6)
            int num = r.nextInt(6);
            for (int i = 0; i < index ; i++) {
                if(num == arr[i]) {
                    continue w;
                }
            }
            arr[index] = num;
            index++;
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

  • Option II
import java.util.Random;
public class RandomTest03 {
    public static void main(String[] args) {

        int[] arr = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = -1;
        }

        Random r = new Random();

        int index = 0;
        while(index < arr.length){
            int n = r.nextInt(6);
            if(!contains2(arr,n)){       //这里因为判断一个数字是否在一个数组不好写,所以单独写了一个判断的方法
                arr[index++] = n;
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
//这是我写的判断方法,其实写的复杂了。可以改为下面注释掉的方式
    public static boolean contains(int[] a, int num) {
        int i;
        for (i = 0; i < a.length; i++) {
            if (a[i] == num) {
                break;
            } else {
                continue;
            }
        }
        if (i == a.length) {
            return false;
        } else {
            return true;
        }

	
       /*for(int j = 0;j < a.length; j++){
          if(a[j] == num){
              return true;
          }
        }
        return false; */ 
  • Scheme Three: based on dichotomy (present bug)

Here only part of the code judgment is posted, the body portion as with the above two methods. This approach seems simple and perfect, but the actual operation found bug: array output in the first two elements will always be -1, which is a dichotomy because every sort will disrupt the order of the original array caused!

So the program is not available!

public static boolean contains2(int[] a, int num){  //这种方案有 bug,但看起来很妙!,
        Arrays.sort(a);     //这里的排序会导致前两个数永远是 -1
        int index = Arrays.binarySearch(a,num);
        if (index >= 0){
            return true;
        }else {
            return false;
        }
    }

Guess you like

Origin www.cnblogs.com/yerun/p/12573696.html