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]+"");
        }
    }
}

输出的结果:

相关推荐
邪神与厨二病2 分钟前
牛客周赛 Round 153
python·算法
yaoxin52112310 分钟前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
做个文艺程序员27 分钟前
Linux第24篇:Java应用监控体系搭建:Prometheus+Grafana可视化运维
java·grafana·prometheus
小钻风33661 小时前
Spring Boot 文件上传详解:深入理解 MultipartFile 的使用与原理
java·开发语言
其美杰布-富贵-李1 小时前
Spring Boot 工程开发全流程说明
java·spring boot·后端
qizayaoshuap2 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语3 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet3 小时前
树状结构在查询优化中的作用与实现细节7
算法
前端双越老师3 小时前
如何以前端视角(非0基础)学 Java ?
java·node.js·全栈
dear_bi_MyOnly3 小时前
【SpringBoot配置文件】
java·spring boot·后端·学习·spring·java-ee·学习方法