int[] arr = {1, 2, 3, 4};
int a, b, c;
我想把 数组中 随机取3个数 赋值给abc 其中 1是必须要有的随机赋给abc,然后 2 3 4 随机再赋给其他两个变量,2 3 4 可以重复
例如:
a=1 b=2 c=2
a=2 b=3 c=1
a=3 b=1 c=3
JAVA 数组随机取值
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
threenewbee 2023-07-21 09:43关注import java.util.Random; import java.util.ArrayList; public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; int[] result = new int[3]; Random r = new Random(); ArrayList<Integer> lst = new ArrayList<>(); lst.add(0); lst.add(1); lst.add(2); int idx = r.nextInt(3); result[idx] = arr[0]; lst.remove(Integer.valueOf(idx)); int idx1 = r.nextInt(3) + 1; int idx2 = r.nextInt(3) + 1; result[lst.get(0)] = arr[idx1]; result[lst.get(1)] = arr[idx2]; int a, b, c; a = result[0]; b = result[1]; c = result[2]; System.out.println("a = " + a + ", b = " + b + ", c = " + c); } }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 2无用