当前位置: 代码迷 >> 综合 >> 随机生成 n 个不等整数的 Java 代码实现
  详细解决方案

随机生成 n 个不等整数的 Java 代码实现

热度:91   发布时间:2024-01-16 01:38:04.0

 

昨天看教程时中间布置的题目, 自己也想了好久, 最后还是看了视频解答才想清楚.

这里做下简单回顾:

 

以生成5个为例

 

思路

先生成一个包含 5 个元素的数组对象 a

再生成一个随机数对象 r

利用随机数对象生成第一个随机数给 a[0]

从 a[1] 开始, 每次利用 r 生成新的随机数, 确认与 a 中的元素不同之后, 付给 a[1] a[2] a[3] a[4]

 

编码

以下是第二版代码, 加入了一个 isExists 方法, 用来判断新生成的随机数 temp 是否在数组 a 中已存在.

但是 > 标注处有问题

1. temp 定义在了循环外, 所以它不会随着迭代而变化

2. while 循环成立时会给 a[i] 赋值, 失败则直接跳过了 a[i]

package commonClass;import java.util.Random;public class UnequalRandom {public static void main(String[] args) {// TODO Auto-generated method stubint[] a = new int[5];Random r = new Random();a[0] = r.nextInt(5);>		int temp = r.nextInt(5);
>		for (i = 1; i < a.length; i++) {
>			while (isExists(temp, a)) {
>				a[i] = temp;
>			}
>		}for (int i = 0; i < a.length; i++) {System.out.println(a[i]);}}// 检查 check 是否存在于数组 dstArray 中// false 表示存在// true 表示不存在private static boolean isExists(int check, int[] dstArray) {for (int i = 0; i < dstArray.length; i++) {if (check != dstArray[i]) {continue;}else {return false;}}return true;	}}

 

对应地进行调整

1. while 循环用来判断数组是否已满

2. while 循环内写 if 条件判断, 来进行 数组元素重复判断和写入

3. temp 变量放入循环内部

package commonClass;import java.util.Random;public class UnequalRandom {public static void main(String[] args) {// TODO Auto-generated method stubint[] a = new int[5];Random r = new Random();a[0] = r.nextInt(5);int index = 1;while (index < 5) {int temp = r.nextInt(5);if(isExists(temp, a)) {a[index++] = temp;}}for (int i = 0; i < a.length; i++) {System.out.println(a[i]);}}// 检查 check 是否存在于数组 dstArray 中// false 表示存在// true 表示不存在private static boolean isExists(int check, int[] dstArray) {for (int i = 0; i < dstArray.length; i++) {if (check != dstArray[i]) {continue;}else {return false;}}return true;	}}

改完后运行, 发现程序一直在运行, 没有输出.

思考一番后没头绪, 所以去参考了讲师给的答案.

讲师同样写了一个判断是否 temp 是否存在于 a 的方法, 但是与本人不同的是, 他多加了一个 a[i] != 0 的判断.

此时才明白, 动态初始化数组对象时, 数组里面的元素都是 0 , 所以除非 a[0] = 0 , 否则会导致 while 循环一直无法结束.

讲师的这种处理方法是除去了新建数组时预赋的 0 , 把取值范围定为 1~5 .

当然也能让程序取 0~4 , 本人的做法是把数组中的元素都先赋值为取值范围外的一个数.

package commonClass;import java.util.Random;public class UnequalRandom {public static void main(String[] args) {// TODO Auto-generated method stubint[] a = new int[5];Random r = new Random();a[0] = r.nextInt(5);int index = 1;/*这里我先把数组的初始值给改了
*/for (int i = 1; i < a.length; i++) {a[i] = a.length;}while (index < 5) {int temp = r.nextInt(5);if(isExists(temp, a)) {a[index++] = temp;}}for (int i = 0; i < a.length; i++) {System.out.println(a[i]);}}// 检查 check 是否存在于数组 dstArray 中// false 表示存在// true 表示不存在private static boolean isExists(int check, int[] dstArray) {for (int i = 0; i < dstArray.length; i++) {if (check != dstArray[i]) {continue;}else {return false;}}return true;	}}