Java打乱数组元素

java 复制代码
package com.mohuanan.exercise;

import java.util.Random;

//打乱数组的元素
public class ExerciseDemo05 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        Random r = new Random();

        for (int i = 0; i < arr.length; i++) {
            int randomIndex = r.nextInt(5);
            int temp;//临时变量
            temp = arr[randomIndex];
            arr[randomIndex] = arr[i];
            arr[i] = temp;
        }
        //遍历数组,并输出

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+"");
        }
    }
}

输出的结果:

相关推荐
小溪学编程13 小时前
Java InputStream 详解:从基础到实战
java·python·php
血小板要健康13 小时前
队列 + 宽搜(BFS):二叉树层序遍历 算法总结
java·数据结构·笔记·算法·leetcode·宽度优先
Felven14 小时前
A. Riptide
算法·c 算法
m0_7393128714 小时前
四元数、李群SO(3)/李代数so(3)的作用及应用场景
算法·机器人·自动驾驶
A黄俊辉A14 小时前
【无标题】
java
BestHeaker14 小时前
跨企业接口对接:IQDS / CPK 数据解析与协作避坑指南(五)
java·服务器·前端
artificiali14 小时前
880 第4章多元
人工智能·算法
Felven15 小时前
B. Deja Vu
数据结构·算法
俊昭喜喜里15 小时前
C#中的func<>
java·前端·c#
highreport15 小时前
net报表工具对比:HighReport 与 FastReport
java·c#