JAVA练习题36:打乱一维数组中的数据,并按照4个一组的方式添加到二维数组中

这篇博客介绍了如何在Java中使用Random类打乱一维整数数组,然后将打乱后的数组按照4个一组填充到二维数组中。通过示例代码展示了具体的实现步骤,包括数组的初始化、随机交换元素、遍历输出结果以及二维数组的创建和填充方法。这是一次关于数组操作和随机数应用的编程练习。
摘要由CSDN通过智能技术生成

拼图游戏准备工作

练习:打乱一维数组中的数据

  1. int[] tempArr = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
  2. 要求:打乱一维数组中的数据,并按照4个一组的方式添加到二维数组中。
package Test;

import java.util.Random;

public class FTest {
    public static void main(String[] args) {
        /*
         * 练习:打乱一维数组中的数据
         * int[] tempArr = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
         * 要求:打乱一维数组中的数据,并按照4个一组的方式添加到二维数组中。
         * */

        //1.定义一个一维数组
        int[] tempArr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        //2.打乱数组中的数据的顺序
        //遍历数组,得到每一个元素,拿着每一个元素跟随机索引上的数据进行交换
        Random r = new Random();
        for (int i = 0; i < tempArr.length; i++) {
            //获取随机索引
            int index = r.nextInt(tempArr.length);
            //拿着遍历到的每一个数据,跟随机索引上的数据进行交换
            int temp = tempArr[i];
            tempArr[i] = tempArr[index];
            tempArr[index] = temp;
        }
        //3.遍历数组
        for (int i = 0; i < tempArr.length; i++) {
            System.out.print(tempArr[i] + " ");
        }
        System.out.println();
        //4.创建一个二维数组
        int[][] data = new int[4][4];
        //5.给二维数组添加数据
        //解法一:
        //遍历一位数组tempArr得到每一个元素,把每一个元素依次添加到二维数组当中
        for (int i = 0; i < tempArr.length; i++) {
            data[i / 4][i % 4] = tempArr[i];
        }
/*        //解法二:
        //遍历二维数组,给里面的每一个数据赋值
        int index = 0;
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                data[i][j] = tempArr[index];
                index++;
            }
        }*/
        //遍历二维数组
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                System.out.print(data[i][j] + " ");
            }
            System.out.println();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值