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);
        }
相关推荐
NE_STOP6 小时前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
后端AI实验室11 小时前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
程序员清风13 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme13 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Be_Better13 小时前
学会与虚拟机对话---ASM
java
开源之眼15 小时前
《github star 加星 Taimili.com 艾米莉 》为什么Java里面,Service 层不直接返回 Result 对象?
java·后端·github
Maori31616 小时前
放弃 SDKMAN!在 Garuda Linux + Fish 环境下的优雅 Java 管理指南
java
用户9083246027316 小时前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot
小王和八蛋17 小时前
DecimalFormat 与 BigDecimal
java·后端
beata17 小时前
Java基础-16:Java内置锁的四种状态及其转换机制详解-从无锁到重量级锁的进化与优化指南
java·后端