|
发表于 2021-3-31 18:05:20
|
显示全部楼层
自己看吧,详细注释,都在里面,建议楼主多使用现成方法,提高效率和代码可读性!
- package com.lian.convert;
- import com.alibaba.fastjson.JSON;
- import java.util.Arrays;
- /**
- * @author :LSS
- * @description: 创建一个长度为6的 int 型数组,要求取值为1~30,同时元素值各不相同
- * @date :2021/3/31 17:47
- */
- public class TestC {
- public static void main(String[] args) {
- //定义计数器,记录数组中元素个数
- int nums = 0;
- //定义长度为6的int型数组
- int[] arrays = new int[6];
- while (true) {
- //如果元素个数超过6,跳出循环
- if (nums > 5)
- break;
- //随机生成0~30的数并向上取整,之后转换为int类型
- int random = (int) Math.ceil(Math.random() * 30);
- //判断数组中是否已经存在该元素,如果不存在,将值放进数组中,计数器加一
- if (!Arrays.asList(arrays).contains(random)) {
- arrays[nums] = random;
- nums++;
- }
- }
- //打印查看数组
- System.out.println(JSON.toJSONString(arrays));
- }
- }
复制代码 |
|