qq_39551237 2023-07-21 09:31 采纳率: 70%
浏览 34
已结题

JAVA 数组随机取值

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

  • 写回答

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条)

报告相同问题?

问题事件

  • 系统已结题 7月29日
  • 已采纳回答 7月21日
  • 创建了问题 7月21日