package lianxi; import java.util.Random; public class suijishu { public static void main(String[] args) { Random random = new Random(); int[] arr = new int[4]; arr[0] = random.nextInt(9); int i = 1; //外循環定義四個數 while(i <=3) { int x = random.nextInt(9); /*內循環:新生成隨機數和已生成的比較, *相同則跳出內循環,再生成一個隨機數進行比較 *和前幾個生成的都不一樣則這個就是新的隨機數 */ for (int j = 0; j <= i - 1; j++) { //相同則跳出內循環,再生成一個隨機數進行比較 if (arr[j] == x) { break; } //執行完循環和前幾個生成的都不一樣則這個就是新的隨機數 if(j+1==i){ arr[i] = x; i++; } } } //打印出來生成的隨機數 for (int aaa : arr) { System.out.print(aaa); } } }