java初学小笔记1

ChillLee / 2025-01-25 / 原文

只作为完成作业之余穿插一些自己的思考,不保证正确性。

\(\texttt{URL}\)

只作为完成作业之余穿插一些自己的思考,不保证正确性。

Java 常用类

String 类

//javac

String(String str)
// 构造方法:创建一个新的 String 对象, 其值为 str 中的字符

char charAt(int index)
//返回指定索引处的那个字符
//这里注意,与c++的习惯调用方式 str[i] 不同也不兼容

String concat(String str)
//返回一个由本对象字符串与 str 对象字符串拼接后的新字符串

boolean equals(String str)
//如果本对象字符串与 str 对象字符串相同(不区分大小写),返回真,否则返回假

int length()
//返回本对象字符串长度(所包含字符个数)

String replace(char oldChar, char newChar)
//返回字符串中所有形如 oldChar 的字符串用新字串 newChar 替换后,构造新字符串对象返回

String substring(int offset, int endIndex)
//返回字符串中从索引 offset 开始,到 endIndex-1 的子串

String toLowerCase()
//将字符串中的所有大写字母转换成对应的小写字母后,返回该字符串

String toUpperCase()
//将字符串中的所有小写字母转换成对应的大写字母后,返回该字符串

indexOf 方法

//javac

# indexOf 方法有几个不同的重载版本:

//注:如果未找到该字符或子字符串,则返回 -1。

indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
indexOf(int ch, int fromIndex):返回指定字符在此字符串中第一次出现处的索引,从指定的索引开始搜索。
indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引。
indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始搜索。

# 示例:
public class Main {
    public static void main(String[] args) {
        String str = "Hello, World! World!";
        int index = str.indexOf("World", 8); // 从索引8开始查找子字符串 "World"
        System.out.println("Index of 'World' starting from index 8: " + index); // 输出 12
    }
}

split 方法

\(\text{Java}\) 中,split 方法是 \(\text{String}\) 类的一部分,用于将字符串按照指定的分隔符拆分成字符串数组。以下是 split 方法的基本用法:

//javac

String str = "one,two,three";
String[] arr = str.split(","); // 使用逗号作为分隔符

for (String element : arr) {
    System.out.println(element);
}
// 在上面的例子中,字符串 "one,two,three" 被逗号 , 分隔,并被拆分成一个包含三个元素的字符串数组("one", "tow", "three");
# split 方法有以下两个变体:

split(String regex):使用正则表达式作为分隔符来拆分字符串。
split(String regex, int limit):除了使用正则表达式作为分隔符外,还可以指定拆分后 **结果数组** 的最大长度。如果限制 n 大于 0,则结果数组最多包含 n 个元素,最后一个元素包含所有超出最后分隔符的字符。
以下是一些使用 split 方法的示例:

使用单个字符分隔符
String str = "apple#banana#cherry";
String[] arr = str.split("#");

使用正则表达式分隔符
String str = "apple banana cherry";
String[] arr = str.split("\\s+"); // 使用正则表达式匹配一个或多个空格*

限制拆分后的数组长度
String str = "apple,banana,cherry,dates";
String[] arr = str.split(",", 3); // 限制结果数组长度为3
在这个例子中,数组 arr 将包含三个元素:["apple", "banana", "cherry,dates"]。

需要注意的是,split 方法是基于正则表达式的,因此某些特殊字符(如 |, *, +, 等等)在用作分隔符时需要被转义。例如,如果你想要使用点 . 作为分隔符,你需要写成 split("\\.")**,因为在正则表达式中,点 . 是一个特殊字符,代表任意字符。

*:
在正则表达式中,"\s+“和” "(空格)的作用是不同的。

"\\s+":这是一个正则表达式,用来匹配一个或多个空白字符。在正则表达式中,\s代表任何空白字符,包括空格、制表符(tab)、换行符等。+是一个量词,表示前面的元素可以出现一次或多次。因此,\\s+可以匹配任何长度的空白字符串。
" "(空格):这只是一个普通的空格字符,在正则表达式中,它只会匹配字符串中的一个空格字符,而不是空白字符的任意组合。

**:
在正则表达式中,反斜杠(\)是一个转义字符,用于改变其后字符的含义。例如,在正则表达式中,.代表匹配除换行符之外的任何单个字符。

当你在正则表达式中想要匹配一个文字的点(.)字符时,你需要使用反斜杠来转义它,因为点在正则表达式中有特殊的含义。因此,你应该写成\.。

然而,在Java字符串字面量中,反斜杠也是一个转义字符。当你把一个包含反斜杠的字符串传递给正则表达式时,Java解释器会首先对字符串中的反斜杠进行解析。这意味着,如果你只写\.,Java会将其解释为一个转义序列,并且.不会被正则表达式引擎解释为文字的点。

因此,为了确保正则表达式引擎接收到一个文字的点,你需要对反斜杠本身进行转义,也就是使用两个反斜杠\\.:

第一个反斜杠(\)是Java字符串字面量中的转义字符,用于告诉Java解释器,接下来的字符应该按字面意义处理。
第二个反斜杠(\)是正则表达式中的转义字符,用于告诉正则表达式引擎,.应该按字面意义处理,而不是作为一个通配符。

Math 类

//javac

double sqrt(double a)
// 返回正确舍入的a的平方根

double random()
// 返回带正号的double值,大于等于0.0且小于1.0

int max(int a, int b)
// 返回两个int值中的较大值

int min(int a, int b)
// 返回两个int值中的较小值

double pow(double a, double b)
// 返回a的b次幂的值

long round(double a)
// 返回最接近参数并等于某一整数的long值,如果两个整数的距离相等,则返回偶数

StirngBuilder 类

//javac

StringBuilder append(String str)
// 将指定的字符串追加到此字符序列

StringBuilder insert(int offset, String str)
// 将字符串插入到此字符序列中

StringBuilder delete(int start, int end)
// 删除此序列的子字符串中的字符

StringBuilder replace(int start, int end, String str)
// 使用指定的String替换此序列的子字符串中的字符

StringBuilder reverse()
// 导致此字符序列被反转

String toString()
// 返回此序列中数据的字符串表示形式

作业代码

代码1

我们写一个判断回文的类

//javac

import java.util.Scanner;
public class JudgePalindrome {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        if(isPalindrome(str)){
            System.out.println("yes");
        }
        else System.out.println("no");
    }
    public static boolean isPalindrome(String str){
        return str.equals(new StringBuilder(str).reverse().toString());
    }
}

代码2

我们以 7-15 复数四则运算 这道模拟题为例,来学习使用、构造类

题面

本题要求编写程序,计算2个复数的和、差、积、商。

输入格式:

输入在一行中按照a1 b1 a2 b2的格式给出2个复数C1=a1+b1i和C2=a2+b2i的实部和虚部。题目保证C2不为0。

输出格式:

分别在4行中按照(a1+b1i) 运算符 (a2+b2i) = 结果的格式顺序输出2个复数的和、差、积、商,数字精确到小数点后1位。如果结果的实部或者虚部为0,则不输出。如果结果为0,则输出0.0。

输入样例1:

2 3.08 -2.04 5.06

输出样例1:

(2.0+3.1i) + (-2.0+5.1i) = 8.1i
(2.0+3.1i) - (-2.0+5.1i) = 4.0-2.0i
(2.0+3.1i) * (-2.0+5.1i) = -19.7+3.8i
(2.0+3.1i) / (-2.0+5.1i) = 0.4-0.6i

输入样例2:

1 1 -1 -1.01

输出样例2:

(1.0+1.0i) + (-1.0-1.0i) = 0.0
(1.0+1.0i) - (-1.0-1.0i) = 2.0+2.0i
(1.0+1.0i) * (-1.0-1.0i) = -2.0i
(1.0+1.0i) / (-1.0-1.0i) = -1.0

代码

//javac

import java.util.Scanner;

public class ComplexArithmeticOperations{

    // 类似c++结构体,我们定义一个 num 类来封装两复数加减乘除的做法
    public static class num{ 
        double real;//非静态变量
        double ima;

        public num(double real, double ima){ // 构造函数
            this.real = real;
            this.ima = ima;
        }

        // this.* 是第一个数的成员变量, other.* 是第二个数的成员变量

        public num add(num other) { //addition 处理加法
            return new num(this.real + other.real, this.ima + other.ima);
        }

        public num subt(num other){ // subtraction 处理减法
            return new num(this.real - other.real, this.ima - other.ima);
        }
        public num mul(num other){ // 处理乘法
            return new num(this.real* other.real - this.ima* other.ima, this.ima*other.real + this.real* other.ima);
        }
        public num div(num other){ // 处理除法
            num tmp = new num(other.real, -1.0*other.ima); // 我们要先使分母有理化,为此需要声明一个新的 tmp 构造为分母的共轭复数
            other = tmp.mul(other); // 分母有理化过程,此条语句结束后,分母有理
            return new num((this.real* tmp.real - this.ima* tmp.ima)/other.real, (this.ima*tmp.real + this.real* tmp.ima)/other.real);
        }
    }


    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        num a = new num(scan.nextDouble(), scan.nextDouble());
        num b = new num(scan.nextDouble(), scan.nextDouble());

        scan.close();

        add(a, b);

        subt(a, b);

        mul(a, b); //

        div(a, b);
    }

    // 根据题目要求精度,四舍五入
    public static num toOne(num x){
        return new num(Math.round(x.real * 10.0) / 10.0, Math.round(x.ima * 10.0) / 10.0);
    }

    public static void add(num a, num b){
        num ans = a.add(b);
        //System.out.printf("(%f", a.real, a.ima, b.real, b.ima);
        printNum(toOne(a));
        System.out.print(" + ");
        printNum(toOne(b));
        System.out.print(" = ");
        printAns(toOne(ans));
        //printTest(ans);
    }
    public static void subt(num a, num b){
        num ans = a.subt(b);
        printNum(toOne(a));
        System.out.print(" - ");
        printNum(toOne(b));
        System.out.print(" = ");
        printAns(toOne(ans));
        //System.out.printf("%f %f \n", ans.real, ans.ima);
    }
    public static void mul(num a, num b){//Multiplication
        num ans = a.mul(b);
        printNum(toOne(a));
        System.out.print(" * ");
        printNum(toOne(b));
        System.out.print(" = ");
        printAns(toOne(ans));
    }
    public static void div(num a, num b){
        num ans = a.div(b);
        printNum(toOne(a));
        System.out.print(" / ");
        printNum(toOne(b));
        System.out.print(" = ");
        printAns(toOne(ans));
    }

    public static void printTest(num x){
        System.out.printf("%f %f \n", x.real, x.ima);
    }

//考虑有0
    public static void printNum(num x){
        final double eps = 1e-10;
        System.out.printf("(%.1f", x.real);
        if(x.ima >= 0) System.out.print("+");
        System.out.printf("%.1fi)", x.ima);
    }

    public static void printAns(num ans){
        boolean flag = false;
        final double eps = 1e-1;
        if(Math.abs(ans.real) > eps) {
            System.out.printf("%.1f", ans.real);
            flag = true;
        }
        if(ans.ima >= eps && flag) System.out.print("+");
        if(Math.abs(ans.ima) > eps) {System.out.printf("%.1fi", ans.ima); flag = true;}

        if(!flag){System.out.print("0.0");}
        System.out.println();
    }
}