logo 范 · 拾光录
网址收集 关于作者 Github Gitee
杂文随笔4
Hexo博客:基础使用Hexo博客:Next主题Hexo博客:Next进阶使用Hexo博客:Next高级配置
前端编程3
前端基础知识16
UniApp15
Vue框架19
Java编程7
Java基础知识14
SpringBoot31
SpringMVC14
MyBatis8
SpringCloud15
RocketMQ1
MyCat1
数据库4
MySQL6
Redis7
MongoDB10
H21
Java技术栈4
知识整理分布式锁的实现方案MySQL事务MySQL的锁
软件工具箱14
IDEAGitMavenGradleNginx安装Nginx配置JMeter压测OllamaPicGoRustFSVSCodeDockerObsidianObs录制
Linux知识11
树莓派安装及使用ArchLinux:常用软件ArchLinux:基础系统安装ArchLinux:深度优化ArchLInux:图形化界面安装ArchLinux:Nirifrp内网穿透Jar启动脚本Linux常用命令VirtualBox安装CentOSVirtualBox安装Ubuntu
Python编程6
Python基础知识Python语法yolo目标检测OpenCV的使用及树莓派平台condauv
创意设计2
Blender:入门知识UI设计基础知识
AI相关9
Claude CodeHermes AgentOpenAI基本使用OpenAI工具调用OpenAI记忆管理OpenAI推理执行OpenAI开发框架Langchainllama.cpp

随机数的产生方式

Random()

Random random = new Random()
random.nextInt(100) // [0,100)的随机数

区间随机数公式

random.nextInt(max - min + 1) + min

Math.random()

该方法随机返回[0.0,1.0)的double型数值,由于double类数的精度很高,可以在一定程度下看做随机数,借助int来进行类型转换就可以得到整数随机数

currentTimeMillis()

不常用,也是一种方法,使用当时时间戳进行取模运算

public static void main(String[] args) {    
    int max=100,min=1;
    long randomNum = System.currentTimeMillis();  
    int ran3 = (int) (randomNum%(max-min)+min);  
    System.out.println(ran3);      
}

使用Math类处理分页计算

pageSize = Math.max(pageSize, 1);
long maxPage = (long) Math.ceil(count / (float) pageSize);
pageIndex = Math.max(Math.min(pageIndex, maxPage), 1);

注意:这是超过页数后返回最大页的情况,APP是不需要这样操作的

Math.round()

四舍五入,该函数返回的是一个四舍五入后的的整数

Math.ceil()

向上取整,即小数部分直接舍去,并加1

double d5 = -16.5;
double ceil5 = Math.ceil(d5);   // 结果 -16.0
double d6 = 16.5;
double ceil6 = Math.ceil(d6);   // 结果 17.0

Math.floor()

向下取整,即小数部分直接舍去

double d5 = -16.5;
double floor5 = Math.floor(d5);   // 结果 -17.0
double d6 = 16.5;
double floor6 = Math.floor(d6);   // 结果 16.0

BigDecimal基础操作

// 创建方式,数字使用字符串
BigDecimal bd = new BigDecimal("123.4567");

// 加减乘除:
BigDecimal a= new BigDecimal("10");  
BigDecimal b= new BigDecimal("5");  

// 加法
a.add(b);  

// 减法  
a.subtract(b);

// 乘法  
a.multiply(b);
 
// 除法  
a.divide(b);

if(a.compareTo(b) == -1){
    System.out.println("a小于b");
}

if(a.compareTo(b) == 0){
    System.out.println("a等于b");
}

if(a.compareTo(b) == 1){
    System.out.println("a大于b");
}

if(a.compareTo(b) > -1){
    System.out.println("a大于等于b");
}

if(a.compareTo(b) < 1){
    System.out.println("a小于等于b");
}

时间格式化

日期转时间戳

SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
String time="2020-12-29 20:40:00";  
Date date = format.parse(time);  
//日期转时间戳(毫秒)
long time=date.getTime()
System.out.print("Format To times:"+time);

时间戳转换为时间

String time="2018-09-29 16:39:00";  
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(time);
Date date = new Date(lt);
//日期格式化
String  res = simpleDateFormat.format(date);
System.out.print("Format To times:"+res ); 

日期与字符互转

Date date = new Date();
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
String dateStr = simpleDate.format(date);

Date parse = new SimpleDateFormat("HH:mm:ss").parse("09:00:00");

使用枚举定义全局状态

/**
 * 全局状态变量
 */
public enum GlobalStatus {

    /**
     * 通用状态:审核
     */
    STATUS_AUDIT(0),

    /**
     * 通用状态:正常
     */
    STATUS_NORMAL(1),

    /**
     * 通用状态:关闭
     */
    STATUS_CLOSE(2),

    /**
     * 通用状态:删除
     */
    STATUS_DELETE(3);

    private final int value;

    GlobalStatus(int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }

}

使用方式

GlobalStatus.STATUS_DELETE.value()

URL地址网络传输处理

在网络的传输中,接口直接响应URL字符串在浏览器中会被转义,就会出现一些意料之外的问题,推荐将其encode进行传输

后端Java处理

// 编码
String str = URLEncoder.encode("中国","utf-8");
System.out.println(str);

//解码
String str1=URLDecoder.decode(str, "UTF-8");
System.out.println(str1);

前端JS处理

//编码
encodeURIComponent()
//解码
decodeURIComponent()

根据概率随机抽奖模拟

在抽奖等类似的场景下,都会控制抽奖的概率,如何简单模拟概率的控制?

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

public class LotteryDemo {

    public static void main(String[] args) {
        Random random = new Random();
        // 奖品名称,几率
        Map<String, Integer> prize = new LinkedHashMap<>();
        prize.put("手机", 20);
        prize.put("电脑", 40);
        prize.put("平板", 20);
        prize.put("耳机", 20);
        // 区间在0~9999
        int ram = random.nextInt(10000);
        System.out.println("随机数:" + ram);
        int start = 0;
        for (String name : prize.keySet()) {
            Integer end = prize.get(name);
            start += end * 100;
            if (ram < start) {
                System.out.println("奖品是:" + name);
                return;
            }
        }
        System.out.println("未中奖");
    }

}

获取网络图片的宽和高

在一次业务场景中,需要对请求的url图片宽高做显示,那就需要对图片的宽高做获取

@Test
void ImageWidthAndHeight() {
    try {
        InputStream is = new URL(url).openStream();
        BufferedImage sourceImg = ImageIO.read(is);
        int width = sourceImg.getWidth();
        int height = sourceImg.getHeight();
        System.out.println(width);
        System.out.println(height);
        double ratio = (double) width / height;
        String format = new DecimalFormat("0.##").format(ratio);
        Assert.isTrue(Objects.equals(format, "1.92") || Objects.equals(format, "1.93"), "封面宽高比例需要100:192");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

post请求FormData

// 数据上传
try {
//    URL url = new URL("https://xishangkeji.com/schoolapiadmin/external/pass/epc");
    URL url = new URL("http://127.0.0.1:8998/external/pass/epc");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setDoOutput(true);

    Map<String, String> params = new HashMap<>();
    params.put("epc", epc);
    params.put("schoolId", schoolId);
    params.put("scene", scene);
    params.put("way", String.valueOf(passType));


    // 构建参数字符串
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String, String> param : params.entrySet()) {
        if (postData.length() != 0) {
            postData.append('&');
        }
        postData.append(param.getKey())
                .append('=')
                .append(java.net.URLEncoder.encode((String) param.getValue(), "UTF-8"));
    }

    // 发送请求
    try (OutputStream output = connection.getOutputStream()) {
        output.write(postData.toString().getBytes(StandardCharsets.UTF_8));
    }

    // 读取响应
    int responseCode = connection.getResponseCode();
    BufferedReader reader;
    if (responseCode == 200 || responseCode == 201) {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } else {
        reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
    }
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    reader.close();
    System.out.println(response);

} catch (Exception e) {
    e.printStackTrace();
}
随机数的产生方式
Random()
Math.random()
currentTimeMillis()
使用Math类处理分页计算
Math.round()
Math.ceil()
Math.floor()
BigDecimal基础操作
时间格式化
日期转时间戳
时间戳转换为时间
日期与字符互转
使用枚举定义全局状态
URL地址网络传输处理
根据概率随机抽奖模拟
获取网络图片的宽和高
post请求FormData