Random类和String类

Random类:

java.util.Random类

生成随机数:

上面的Math类的random()方法也可以产生随机数,其实Math类的random()方法底层就是用Random类实现的。

复制代码
Random rand = new Random();  //创建一个Random对象
获取随机数的方法:

|---------------------|---------------|
| int nextInt(); | 返回下一个随机数 |
| int nextInt(int n); | 返回0到n-1之间的随机数 |

例子:生成0-20随机数:
复制代码
public static void main(String[] args) {
        Random rand = new Random();
        //生成20个随机数并且显示
        for (int i = 0; i<20;i++){
            int num = rand.nextInt(10);
            System.out.println("第"+i+"个随机数是:"+num);
        }
    }
种子值:

用同一个种子值来初始化两个Random 对象,然后用每个对象调用相同的方法,得到的随机数也是相同的。

种子的数值不同代表不同的状态,没什么实际意义

复制代码
 public static void main(String[] args) {
        // 使用相同的种子值初始化两个 Random 对象
        long seed = 42;
        long seed2 = 23;
        Random random1 = new Random(seed);
        Random random2 = new Random(seed);
        // 打印两个 Random 对象的随机数
        System.out.println("Random1: " + random1.nextInt(100));
        System.out.println("Random2: " + random2.nextInt(100));
        // 再次打印,看看结果是否一致
        System.out.println("Random1: " + random1.nextInt(100));
        System.out.println("Random2: " + random2.nextInt(100));

         Random random3 = new Random(seed2);
         System.out.println(random3.nextInt(200));
         System.out.println(random3.nextInt(200));
     
    }

String类:

String类位于java.lang包中,具有丰富的方法计算字符串的长度、比较字符串、连接字符串、提取字符串

1.length()方法:

返回字符串中的字符数

2.equals( )方法

比较存储在两个字符串对象的内容是否一致

比较原理:检查组成字符串内容的字符是否完全一致

"=="和equals()区别:

==:判断两个字符串在内存中的地址,即判断是否是同一个字符串对象

字符串比较的其他方法:
使用equalsIgnoreCase()忽略大小写:
复制代码
public static void main(String[] args) {
        String str1 = "AsapBayby";
        String str2 = "asApBayBy";
        if (str1.equalsIgnoreCase(str2)){
            System.out.println("忽略大小写相等");
        }
    }
使用toLowerCase()小写:

比较方法:str1.toLowerCase().equals(str2.toLowerCase())

复制代码
 public static void main(String[] args) {
        String str1 = "AsapBayby";
        String str2 = "asApBayBy";
        if (str1.toLowerCase().equals(str2.toLowerCase())){
            System.out.println("都转成小写相同");
            System.out.println(str2);
        }else {
            System.out.println("忽略大小写不相等");
        }

    }
使用toUpperCase()大写:

同理,比较条件换成:

复制代码
 if (str1.toUpperCase().equals(str2.toUpperCase())){
            System.out.println("都转成大写相同");
            System.out.println(str2);
        }
相关推荐
披着羊皮不是狼8 分钟前
多用户跨学科交流系统(4)参数校验+分页搜索全流程的实现
java·spring boot
AI_567828 分钟前
接口测试“零基础通关“:Postman从入门到自动化测试实战指南
开发语言·lua
是Yu欸36 分钟前
Rust 并发实战:从零构建一个内存安全的“番茄时钟”
开发语言·安全·rust
小池先生43 分钟前
Gradle vs Maven 详细对比
java·maven
q***23921 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
q***78781 小时前
Spring Boot的项目结构
java·spring boot·后端
应用市场1 小时前
Qt QTreeView深度解析:从原理到实战应用
开发语言·数据库·qt
q***96581 小时前
Spring Data JDBC 详解
java·数据库·spring
ooooooctober1 小时前
PHP代码审计框架性思维的建立
android·开发语言·php
Kuo-Teng1 小时前
LeetCode 118: Pascal‘s Triangle
java·算法·leetcode·职场和发展·动态规划