随机数
java.util.Random;示例代码:
Random r1 = new Random(); System.out.println(r1.nextInt(101)); // 选择0-101之间的数字 // 循环生成5个随机数 for (int i = 0; i < 5; i++) { System.out.println(r1.nextInt(101)); }
exercise:生成5个不重复的数
// 生成【1-5】个不重复的随机数 Random r2 = new Random(); int[] i1 = new int[5]; int index = 0; while (index < 5) { int temp = r2.nextInt(6); System.out.println("___________________________________"); if (temp != 0 && !contains(i1, temp)) { System.out.println("||||||||||||||||||||||||||||||||||||||"); i1[index++] = temp; } } // 遍历 for (int i = 0; i < i1.length; i++) { System.out.println(i1[i]); } public static boolean contains(int[] a, int b) { for (int i = 0; i < a.length; i++) { if (a[i] == b) { return true; } } return false; }