javase-day01

aException_Exception01

package com.se.aException;


/**
 *  异常,Exception,父类Throwable。与其平级的是Error(Error错误,程序员无法处理,属于JVM级别的错误)
 *     1. 程序员可以处理异常。如果不处理,即JVM帮忙处理,简单粗暴,就是终止程序的运行
 *     2. 所以,程序员应该处理异常,不然的话,客户体验非常差
 *     3. Exception的分类:
 *            -运行时异常 RuntimeExcption  非检查型异常
 *            -非运行时异常 None-RuntimeException  检查型异常
 *     4. 异常处理语法
 *          try {
 *              //可能出现异常的代码
 *          }catch( 异常类型 变量){
 *              //发生了异常并捕获到异常时,要执行的模块
 *          }
 *     5. catch模块执行的时机:
 *         try模块里出现了异常情况,就会执行catch模块
 *          注意  catch里面要写处理语句
 *     6. try-catch不会终止程序的后续代码的执行
 *
 */

public class Exception01 {
    public static void main(String[] args) {
        /*
        * 1. 在执行try里的代码片段时没如果出现了异常信息,JVM会主动帮助创建异常对象
        * 2. catch就好将意向的地址捕获到,赋值给小括号里的变量(类型匹配)
        * 3. 当catch捕获到异常镀锡的地址后,就会执行{}里的逻辑代码,没有捕获到就不执行{}
        * 4. 当执行完catch里的代码后,会继续执行后续代码
        **/
        try {
            int[] num = {1,2,3, 4, 5};
            for (int i = 0; i <= num.length; i++) {
                int a = num[i];
                System.out.println(a);
            }
        }catch (Exception e){
//            System.out.println("数组越界");
            e.printStackTrace();
        }
    }
}

aException_Exception02

package com.se.aException;

/**
 * 处理异常时多catch的情况:
 * 1. 当代码片段中,可能出现多种不同类型的异常时,我们每个异常都想要处理的情况下
 */

public class Exception02 {
    public static void main(String[] args) {
        /**
         *  多catch情况
         *    1. 多个异常类型没有继承关系,书写顺序无所谓
         *     ArrayIndexOutOfBoundsException和NullPointerException
         *    2.一旦有继承关系,必须先写子类型
         *      Exception和NullPointerException
         */
        try {
            int[] nums = new int[5];
            nums[5] = 100;
            String str = null;
            int length = str.length();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组下标越界异常");
        } catch (NullPointerException e) {
            System.out.println("空指针异常");
        } catch (Exception e) {
            System.out.println("其他异常");
        }
        //简化版本1.0   前提条件:处理逻辑一样
        //  没有继承关系的异常类型,可以写在一个catch中,使用 |分隔
        try {
            int[] nums = new int[5];
            nums[5] = 100;
            String str = null;
            int length = str.length();
        } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
            e.printStackTrace();
        }
        //简化版本2.0    前提条件:处理逻辑一样
        //  使用这些异常的共同父类型即可
        try {
            int[] nums = new int[5];
            nums[5] = 100;
            String str = null;
            int length = str.length();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

aException_Exception03

package com.se.aException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * finally模块:
 * 1. 位于try或者catch模块之后
 * 2. 无论try里是否发生了异常,都会执行finall模块
 * 3. 应用场景: finally模块一般用与做流的关闭,其他资源释放等操作
 */

public class Exception03 {
    public static void main(String[] args) throws IOException {
        String[] names = new String[3];
        try {
            String name = names[1];
            int length = name.length();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            names[1] = "hello";
        }
        System.out.println(Arrays.toString(names));
        System.out.println("main over");


        //finally的应用场景: 一般用于流的关闭操作
        InputStream is = null;
        try {
            is = Exception03.class.getClassLoader().getResourceAsStream("");
            BufferedImage image = ImageIO.read(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

aException_Exception04

package com.se.aException;

/**
 *  研究一下finally和return的特点
 *    1. 当try里有return关键字,以及finally模块没有return
 *        先执行finally模块代码,然后再执行try里的return关键字
 *    2. try和finally里都有return,一定执行finally里的return
 */

public class Exception04 {
    public static void main(String[] args) {

        int result = test4();
        System.out.println(result);
    }

    public static int test4() {
        //finally 语句块中有 return 语句
        int i = 1;
        try {
            i++;
            System.out.println("try block, i = " + i);
            return i;
        } catch (Exception e) {
            i++;
            System.out.println("catch block i = " + i);
            return i;
        } finally {
            i++;
            System.out.println("finally block i = " + i);
            return i;
        }
    }

    public static int test3() {
        //try 语句块中有 return 语句时的整体执行顺序
        int i = 1;
        try {
            i++;
            System.out.println("try block, i = " + i);
            return i;
        } catch (Exception e) {
            i++;
            System.out.println("catch block i = " + i);
            return i;
        } finally {
            i = 10;
            System.out.println("finally block i = " + i);
        }
    }

    public static int test2() {
        int i = 1;
        try {
            i++;
            throw new Exception();
        } catch (Exception e) {
            i--;
            System.out.println("catch block i = " + i);
        } finally {
            i = 10;
            System.out.println("finally block i = " + i);
        }
        return i;
    }

    public static int test1() {
        int i = 1;
        try {
            i++;
            System.out.println("try block, i = " + i);
        } catch (Exception e) {
            i--;
            System.out.println("catch block i = " + i);
        } finally {
            i = 10;
            System.out.println("finally block i = " + i);
        }
        return i;
    }
}



aException_Exception05

package com.se.aException;

/**
 * 如何自定义异常类型:
 * 1. 继承Exception 或者 RuntimeException,定义两个构造器即可。模拟已经存在的子类异常
 * 2. 继承Exception的自定义异常,是编译时异常
 * 3、 继承RuntimeException的自定义异常,是运行时异常
 *
 * throw 和 throws的特点:
 *  1. throw 是用在方法里,用于将一个异常对象抛出,自己不处理,抛给调用者,谁调用谁就是调用者
 *  2. throws 是用在方法的定义上,表示都告诉调用者需要处理的异常类型
 *  3. throw的如果是编译时异常,必须thorws(必须告诉调用者)
 *     throws 如果是runtimeException,可以不用throws
 */

public class Exception05 {
    public static void main(String[] args) {
        try {
            Person p = new Person("张三", 20);
        } catch (AgeIllegalException e) {
            e.printStackTrace();
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) throws AgeIllegalException {
        this.name = name;
        if (age < 0 || age > 120) {
            throw new AgeIllegalException("年龄不合法");
        }
        this.age = age;
    }
}

class AgeIllegalException extends Exception {
    public AgeIllegalException() {
        super();
    }

    public AgeIllegalException(String message) {
        super(message);
    }
}

bString_StringDemo01

package com.se.bString;

/**
 * 字符串的拼接以及常量池
 *   1.字符串常量池:
 *      JVM为了提升性能和减少内存开销,专门为字符串的一些操作,在内存中专门提供了
 *      一块区域,用于存储字符串对象。该内存区域就是字符串常量池(字符串缓冲区,缓冲池)
 *
 *      什么时候会用到字符串常量池?
 *        当使用字面量给变量赋值时,会先去常量池中寻找是否该字面量的对象,
 *        如果有,就将其地址直接给变量
 *        如果没有,就会在常量池中创建一个该对象,然后将其地址赋值给变量
 */

public class StringDemo01 {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "abc";
        //判定s1和s2是否是同一个对象
        System.out.println(s1 == s2); //true
        //两个字面量做拼接操作时,编译器在编译期间就做了优化操作
        //直接计算出结果 s3 = "abcd"
        String s3 = "abc" + "d";
        String s4 = "abcd";
        System.out.println(s3 == s4); //true

        String s5 = "d";
        //拼接操作只要有变量参与,javac就不会进行优化,只能在运行期间进行计算
        //计算后的几个,储存在堆中,并不是常量池里
        String s6 = "abc" + s5;
        System.out.println(s6 == s4);  //false

        String s7 = "ab" + "c" + s5; // 优化成了"abc"+S5,但是仍然在运算期间与s5做计算,不会去堆里面找,是新对象
        System.out.println(s7 == s6);  //false

        String s8 = new String("d");
        String s9 = "abc" + s8;
        System.out.println(s9 == s7); //false

        String s10 = new String("abc");
        String s11 = new String("abc");


        //假如只有下面代码 问内存里面共有多少对象
        String s12 = "h";
        String s13 = new String( "abc" + s12 +"o") ;
    }
}

bString_StringDemo02

package com.se.bString;

import java.io.UnsupportedEncodingException;

/**
 *  构建字符串对象:
 *   1. 可以直接赋值字面量
 *   2. 也可以调用构造器
 */

public class StringDemo02 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String name = "michael";  //直接赋值字面量
        System.out.println(name);

        //无参构造器,构造的是一个"" 实际上底层是 char[] value = new char[0];
        String str = new String();
        System.out.println(str.length());//0

        //构造器: String(String str)
        String str1 = new String("michael");
        System.out.println(str1);

        //构造器: String(byte[] bytes] : 传入一个字节序列 按照默认字符集转成对应字符
        byte[] bytes2 = {-28,-72,-83,-27,-101,-67};
        String str2 = new String(bytes2);
        System.out.println(str2);

        //构造器: String(byte[] bytes, String charsetName)
        String str3 = new String(bytes2, "UTF-8");
        System.out.println(str3);

        //构造器: String(byte[] bytes, int offset, int length)
        String str4 = new String(bytes2, 3, 3);
        System.out.println(str4);

        //构造器: String(char[] value)
        String str5 = new String(new char[]{'h','e','l','l','o'});
        System.out.println(str5);
    }
}

bString_StringDemo03

package com.se.bString;

import java.util.Arrays;

/**
 * 字符串的常用方法:
 */

public class StringDemo03 {
    public static void main(String[] args) {
        //length方法
        String s1 = "welcome to China";
        System.out.println(s1.length());

        /*
         使用indexOf实现检索
            用于检测子字符串所在的位置,如果没找到,返回-1
            int indexOf(String str)
            int index0f(string str,int fromIndex)
         */
        int index = s1.indexOf("come");
        System.out.println("index is"+index);
        //找到第二个o的下标
        index = s1.indexOf("o",s1.indexOf("0")+1);
        System.out.println("index is"+index);

        /*
            检索子字符串最后一次出现的索引
            int lastIndexOf(String str)
            int lastIndexOf(String str,int fromIndex)
                检索子串最后出现的位置,从左到右一直到指定位置endIndex
         */
        index = s1.lastIndexOf("o");
        System.out.println("index is"+index);
        index = s1.lastIndexOf("o",8);
        System.out.println("index is"+index);

        /*
        使用substring获取子串
            String substring(int beginIndex)
            String substring(int beginIndex,int endIndex)
         */
        String substring = s1.substring(11);
        System.out.println(substring);
        String substring1 = s1.substring(8, 10);
        System.out.println(substring1);

        /*
         trim截掉空格
            trim:去掉字符串两端的空格
            String trim()
         */
        String s2 = "  micheal  ";
        System.out.println(s2.length());
        s2 = s2.trim();
        System.out.println(s2.length());

        /*
        char charAt 获取字符:
            获取指定下标上的字符  可用于单个字符的字符串转成字符类型
            char charAt(int index)
         */
        char c = s1.charAt(1);
        System.out.println(c);

        /*
        startsWith和endsWith
            boolean startsWith(String str) 判断指定子串开头
            boolean endsWith(String str)  判定字符指定结尾
         */
        boolean we = s1.startsWith("we");
        System.out.println(we);
        boolean end = s1.endsWith("ina");
        System.out.println(end);

        /*
            String toUpperCase() 将字符串转换为大写
            String toLowerCase() 将字符串转换为小写
         */
        String s3 = "你好WelCome";
        s3 = s3.toUpperCase();
        System.out.println(s3);
        s3 = s3.toLowerCase();
        System.out.println(s3);

        /*
        toCharArray
            char[] toCharArray() 将字符串转换为字符数组
         */
        char[] charArray = s1.toCharArray();
        System.out.println(charArray);
        System.out.println(Arrays.toString(charArray));

        /*
        valueOf
           下面的方法是静态的,使用类名调用,作用是将参数类型转成字符串形式
            static String valueOf(int value)
            static String valueOf(double d)
            static String valueOf(char[] ch)
            static String valueOf(Object obj)
         */
        String num = String.valueOf(123);

        /*
        equals与==
            equals:比较两个对象的属性是否一样,不是地址值
                ==:比较两个对象的地址值
         */
        String s10 = new String("hello");
        String s11 = new String("hello");
        System.out.println(s10 == s11); //flase
        System.out.println(s10.equals(s11)); //true

    }
}

bString_StringDemo04StringBuilder

package com.se.bString;

/**
 *  因为直接操作String类型,会造成大量的对象在内存里出现,所以影响性能
 *
 *   可以使用StringBuilder或者stringBuffer来操作字符串的拼接,替换,截断等操作
 *   因为: StringBuilder和StringBuffer都是可变字符串类型。
 *   拼接,替换,截断等操作,不会产生新的对象,而是直接在原来的对象上进行操作
 */

public class StringDemo04StringBuilder {
    public static void main(String[] args) {
        /*
            构造器
            StringBuilder()  构建一个空字符串的StringBuilder对象
                         注意:其内部属性的char[]长度是16
            StringBuilder(String str)
         */
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder("");

        /*
         * 常用方法:
         * StringBuilder  append(String str)
         * StringBuilder  insert(int index,String str)
         * StringBuilder	delete(int  start ,  int  end)
         * StringBuilder	 reverse()
         * String	toString()
         */
        StringBuilder s3 = s1.append("欢迎"); //return this
        System.out.println(s1 == s3); //true
        s1.append("来到中国").append(",中国是美丽的").append(",地大物博的");
        System.out.println(s1.toString());

        s1.insert(4, "伟大的");
        System.out.println(s1.toString());

        s1.delete(13, 17);
        System.out.println(s1.toString());

        s1.replace(4, 6, "美丽");
        System.out.println(s1.toString());

        s1.reverse();
        System.out.println(s1.toString());

    }
}

cRegex_RegexDemo01

package com.se.cRegex;

/**
 * 正则表达式;
 *   1. 正则表达式是一个特殊的字符串,可以对普通的字符串进行校验,检验等
 *   2. 它是一套独立的语法,不是某一个编程语言里独有的,
 *       因此大多数编程语言都可以拿过来使用。
 */

public class RegexDemo01 {
    public static void main(String[] args) {
        /**
         * 字符集合
         * [] : 表示匹配括号里的任意一个字符。
         * [abc] :匹配a 或者 b 或者 c
         * [^abc] : 匹配任意一个字符,只要不是a,或b,或c 就表示匹配成功
         * [a-z] : 表示匹配所有的小写字母的任意一个。
         * [A-Za-z] :表示匹配所有的小写字母和大写字母的任意一个。
         * [a-zA-Z0-9]:表示匹配所有的小写字母和大写字母和数字的任意一个。
         * [a-z&&[^bc]] :表示匹配所有的小写字母除了b和c, 只要匹配上就是true.
         */
        System.out.println("a".matches("[abcdefg]"));  //ture

        String regex = "[^hg]";
        String str = "o";
        System.out.println(str.matches(regex)); //true

        //匹配+是不是匹配任意字符
        System.out.println("+".matches("."));  //true

        System.out.println(".".matches("."));  //true

        //    \\. 通配符.变成普通的点符号
        System.out.println("-".matches("\\.")); //false

        /**
         * \d:  用于匹配数字字符中的任意一个  相当于[0-9]
         * \w:   匹配单词字符中的任意一个      单词字符就是[a-zA-Z0-9_]
         * \D:   用于匹配非数字字符中的任意一个   相当于[^0-9]
         * \W:   用于匹配非单词字符中的任意一个
         * \s:  用于匹配空格,制表符,退格符,换行符等中的任意一个
         * \S:   用于匹配非空格,制表符,退格符,换行符等中的任意一个
         * . :  用于匹配任意一个字符
         */
        System.out.println("c".matches("[\\w]")); //true
        System.out.println("c".matches("\\w")); //ture

        /**
         * X?   :匹配0个或1个
         * X*   :匹配0个或1个以上
         * x+   :匹配1个以上
         * X{n} :匹配n个
         * X{m,}:匹配m个以上
         * X{m,n}:匹配m~n个
         */
        //匹配密码: 密码必须是8位的数字或者字符组合
        System.out.println("123ZR678".matches("[a-z A-Z 0-9]{8}")); //
        //匹配用户名: 用户名是由子母数字和下划线组成的 5-8位
        System.out.println("123ZR_68".matches("\\w{5,8}")); //ture

        System.out.println("1".matches("[a-z ]?")); //false
        System.out.println("".matches("[a-z ]?")); //true
        System.out.println("h".matches("[a-z ]?")); //true

        /**
         * ():
         * 在正则表达式上可以使用()来进行对一些字符分组,并可以使用逻辑运算符|来进行选择匹配
         */
        String regex1 = "(13|15|18)(7|8|9)[\\d]{8}";
        String str1 = "15888888888"; //ture
        System.out.println(str1.matches(regex1));
        String str2 = "1558888888"; //false
        System.out.println(str2.matches(regex1));





    }
}

exercise_Exercise01

package com.se.exercise;

import java.util.Scanner;

/**
 * 设计⼀个⽅法,计算从控制台输⼊的两个数字的和,并处理各种输⼊的时候的异常
 * 提示:输入的可能是空格,可能是字母等 至少两个catch
 */

public class Exercise01 {
    /**
     * 计算两个数字的和,并处理输入异常。
     */
    public static void calculateSum() {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("请输入第一个数字: ");
            String firstInput = scanner.nextLine().trim();
            if (firstInput.isEmpty()) {
                throw new IllegalArgumentException("输入不能为空!");
            }
            double firstNumber = Double.parseDouble(firstInput);

            System.out.print("请输入第二个数字: ");
            String secondInput = scanner.nextLine().trim();
            if (secondInput.isEmpty()) {
                throw new IllegalArgumentException("输入不能为空!");
            }
            double secondNumber = Double.parseDouble(secondInput);

            double sum = firstNumber + secondNumber;
            System.out.println("两个数字的和为: " + sum);
        } catch (NumberFormatException e) {
            System.out.println("错误: 输入包含非数字字符,请重新输入数字!");
        } catch (IllegalArgumentException e) {
            System.out.println("错误: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    public static void main(String[] args) {
        calculateSum();
    }
}

exercise_Exercise02

package com.se.exercise;

import java.util.Random;
import java.util.Scanner;

/**
 * 设计⼀个剪⼑⽯头布的⼩游戏
 * 1. ⽤户从控制台输⼊选择: 1. 剪⼑ 2. ⽯头 3. 布
 * 2. 随机⽣成⼀个系统的选择
 * 3. 输出判定结果
 */


public class Exercise02 {
    public static void main(String[] args) {
        // 创建Scanner对象用于读取用户输入
        Scanner scanner = new Scanner(System.in);

        // 创建Random对象用于生成随机数
        Random random = new Random();

        System.out.println("剪刀石头布");
        System.out.println("请输入你的选择: 1. 剪刀 2. 石头 3. 布");

        // 读取用户输入
        int user = scanner.nextInt();

        // 验证用户输入是否合法
        while (user < 1 || user > 3) {
            System.out.println("输入错误,请重新输入: 1. 剪刀 2. 石头 3. 布");
            user = scanner.nextInt();
        }

        // 生成系统的选择
        int ai = random.nextInt(3) + 1;

        // 输出用户和系统的选择
        System.out.println("你的选择是: " + choice(user));
        System.out.println("电脑的选择是: " + choice(ai));

        // 判断胜负并输出结果
        String result = Winner(user, ai);
        System.out.println(result);

        // 关闭scanner
        scanner.close();
    }

    // 将数字转换为对应的字符串
    private static String choice(int choice) {
        switch (choice) {
            case 1:
                return "剪刀";
            case 2:
                return "石头";
            case 3:
                return "布";
            default:
                return "未知";
        }
    }

    // 判断胜负
    private static String Winner(int user, int ai) {
        if (user == ai) {
            return "平局!";
        } else if ((user == 1 && ai == 3) ||
                (user == 2 && ai == 1) ||
                (user == 3 && ai == 2)) {
            return "你赢了!";
        } else {
            return "你输了!";
        }
    }
}


exercise_Exercise03

package com.se.exercise;

import java.util.Random;

/**
 * ⼩明去饭店吃饭,身上带了22块钱,随机产⽣[15, 30]范围的饭钱,如果⼩明的钱不够⽀付饭钱,
 * 抛出⼀个 NotEnoughMoneyException的运⾏时异常。
 */

public class Exercise03 {
    public static void main(String[] args) {
        int money = 22;  // 小明身上的钱
        try {
            dineOut(money);
        } catch (NotEnoughMoneyException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 小明去饭店吃饭的方法。
     *
     * @param money 小明身上的钱
     * @throws NotEnoughMoneyException 如果钱不够支付饭钱
     */
    public static void dineOut(int money) throws NotEnoughMoneyException {
        Random random = new Random();
        int mealCost = random.nextInt(16) + 15;  // 饭钱在 [15, 30] 范围内
        System.out.println("饭钱为: " + mealCost + "元");

        if (money < mealCost) {
            throw new NotEnoughMoneyException("钱不够支付饭钱!");
        } else {
            System.out.println("小明成功支付了饭钱!");
        }
    }

    /**
     * 自定义的运行时异常类。
     */
    public static class NotEnoughMoneyException extends RuntimeException {
        public NotEnoughMoneyException(String message) {
            super(message);
        }
    }
}


exercise_Exercise04

package com.se.exercise;

/**
 * 【简】设计一个方法,将一个字符串中的大小写字母翻转
 * 例如:
 * reverse("heLLo woRld") -> HEllO WOrLD
 */

public class Exercise04 {
    public static String reverseCase(String input) {
        StringBuilder result = new StringBuilder(); // 创建一个 StringBuilder 对象来构建新的字符串

        // 遍历输入字符串中的每个字符
        for (char c : input.toCharArray()) {
            // 检查字符是否为大写
            if (Character.isUpperCase(c)) {
                result.append(Character.toLowerCase(c)); // 如果是大写,则转换为小写并添加到结果中
            } else if (Character.isLowerCase(c)) {
                result.append(Character.toUpperCase(c)); // 如果是小写,则转换为大写并添加到结果中
            } else {
                result.append(c); // 如果不是字母,则直接添加到结果中
            }
        }

        // 返回处理后的字符串
        return result.toString();
    }

    public static void main(String[] args) {
        String original = "heLLo woRld"; // 原始字符串
        String reversed = reverseCase(original); // 调用 reverseCase 方法处理字符串

        // 输出原始字符串和处理后的字符串
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);
    }
}

exercise_Exercise05

package com.se.exercise;

/**
 * 【简】已知方法 trim(String str, char c) 的作用是,去除字符串首尾指定的字符,实现这个方法
 * 例如:
 * trim("aaaahello a worldaaaa", a) -> hello a world
 */

public class Exercise05 {

    public static String trim(String str, char c) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        int start = 0;
        int end = str.length() - 1;

        // 寻找开头处连续出现的指定字符
        while (start <= end && str.charAt(start) == c) {
            start++;
        }

        // 寻找结尾处连续出现的指定字符
        while (end >= start && str.charAt(end) == c) {
            end--;
        }

        // 返回截取后的字符串
        return str.substring(start, end + 1);
    }

    public static void main(String[] args) {
        String original = "aaaahello a worldaaaa";
        char toTrim = 'a';
        String trimmed = trim(original, toTrim);
        System.out.println("Original: " + original);
        System.out.println("Trimmed: " + trimmed);
    }
}


exercise_Exercise06

package com.se.exercise;

import java.util.Random;

/**
 * 【难】给定一个长度,生成一个指定长度的字符串,
 * 这个字符串由随机的字母、数字或下划线组成。(不用必须同时包含字母、数字、下划线)
 * <p>
 * randomString(5) -> hi2Pd
 */

public class Exercise06 {
    public static String randomString(int length) {
        // 定义所有可能的字符集合
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";

        // 创建 StringBuilder 对象来构建新的字符串
        StringBuilder result = new StringBuilder(length);

        // 创建 Random 对象用于生成随机数
        Random random = new Random();

        // 生成指定长度的随机字符串
        for (int i = 0; i < length; i++) {
            // 生成一个介于 0 和 characters.length() 之间的随机索引
            int index = random.nextInt(characters.length());

            // 根据随机索引从 characters 中选择一个字符并添加到 StringBuilder 对象中
            result.append(characters.charAt(index));
        }

        // 返回生成的随机字符串
        return result.toString();
    }

    public static void main(String[] args) {
        int length = 5; // 指定字符串长度

        // 调用 randomString 方法生成随机字符串
        String randomStr = randomString(length);

        // 输出生成的随机字符串
        System.out.println("Generated random string: " + randomStr);
    }
}


exercise_Exercise07

package com.se.exercise;

/**
 * 【中】将一个字符串中最后一次出现的指定字符替换成大小写翻转的字符。
 * <p>
 * replace("hello", 'l') -> helLo
 * replace("HELLO", 'L') -> HELlO
 */

public class Exercise07 {

    /**
     * 将字符串中最后一次出现的指定字符替换为其大小写翻转的形式。
     *
     * @param str 原始字符串。
     * @param ch  需要查找并替换的字符。
     * @return 新的字符串,其中最后一次出现的指定字符已被大小写翻转。
     */
    public static String replaceLastOccurrence(String str, char ch) {
        // 查找字符在字符串中最后一次出现的位置
        int lastIndex = str.lastIndexOf(ch);

        if (lastIndex == -1) {
            // 如果字符未找到,则返回原始字符串
            return str;
        }

        // 将字符转换为其大小写翻转的形式
        char flippedCh = Character.isUpperCase(ch) ? Character.toLowerCase(ch) : Character.toUpperCase(ch);

        // 替换最后一次出现的字符
        return str.substring(0, lastIndex) + flippedCh + str.substring(lastIndex + 1);
    }

    public static void main(String[] args) {
        // 测试用例
        System.out.println(replaceLastOccurrence("hello", 'l')); // 输出: helLo
        System.out.println(replaceLastOccurrence("HELLO", 'L')); // 输出: HELlO
        System.out.println(replaceLastOccurrence("testCASE", 's')); // 输出: testcASE
    }
}


exercise_Exercise08

package com.se.exercise;

import java.util.Scanner;

/**
 * 【难】从控制台输入一个字符串,记录出现次数最多的字符,并输出这个字符出现了多少次
 * <p>
 * 例如:
 * 从控制台输入 hello,输出: 出现次数最多的字符是 'l',出现了2次。
 * 从控制台输入 helle,输出: 出现次数最多是字符出 'l'和'e',出现了2次。
 */


public class Exercise08 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String input = scanner.nextLine();

        findMostFrequentChars(input);
    }

    public static void findMostFrequentChars(String input) {
        // 使用数组来统计每个字符出现的次数
        int[] charCountArray = new int[256]; // 假设使用 ASCII 字符集

        // 统计每个字符出现的次数
        for (char c : input.toCharArray()) {
            charCountArray[c]++;
        }

        // 查找出现次数最多的字符
        int maxCount = 0;
        for (int count : charCountArray) {
            if (count > maxCount) {
                maxCount = count;
            }
        }

        // 记录出现次数最多的字符
        StringBuilder mostFrequentChars = new StringBuilder();
        for (int i = 0; i < charCountArray.length; i++) {
            if (charCountArray[i] == maxCount) {
                mostFrequentChars.append((char) i).append(", ");
            }
        }

        // 输出结果
        if (mostFrequentChars.length() > 0) {
            mostFrequentChars.setLength(mostFrequentChars.length() - 2); // 移除最后的逗号和空格
            System.out.println("出现次数最多的字符是 '" + mostFrequentChars + "',出现了 " + maxCount + " 次。");
        } else {
            System.out.println("没有字符出现。");
        }
    }
}




exercise_Exercise09

package com.se.exercise;

import java.util.Random;

/**
 * 【最难】设计⼀个⽅法,将⼀个数组中的元素随机排列
 */

public class Exercise09 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        shuffle(array);  // 调用 shuffle 方法对数组进行随机排列
        printArray(array);  // 打印排列后的数组
    }

    /**
     * 使用 Fisher-Yates 算法对数组进行随机排列
     *
     * @param array 待排列的数组
     */
    public static void shuffle(int[] array) {
        Random random = new Random();  // 创建 Random 对象用于生成随机数
        for (int i = array.length - 1; i > 0; i--) {
            // 生成一个 [0, i] 区间内的随机索引
            int j = random.nextInt(i + 1);
            // 交换 array[i] 和 array[j]
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }

    /**
     * 打印数组中的元素
     *
     * @param array 待打印的数组
     */
    public static void printArray(int[] array) {
        for (int value : array) {
            System.out.print(value + " ");
        }
        System.out.println();  // 换行
    }
}

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值