[Idea] java interview question: create an int type array with a length of 6, requiring a value of 1-30, and the element values are different

 Ideas:

1. Circulate the array assignment, the range is [1-30]

2. Compare the value assigned for the second time with the previous value one by one, continue the outer loop if different, and continue the outer loop with i-1 (return) until each value is different, then end the loop

public class ArrPratice {
    public static void main(String[] args) {
        int[] arr = new int[6];
        for (int i = 0; i < arr.length; i++) {// [0,1) [0,30) [1,31)
            arr[i] = (int) (Math.random() * 30) + 1;
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    i--;
                    break;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

 

Guess you like

Origin blog.csdn.net/qq_41048982/article/details/109233154