HM-Java Basics-day02 Common APIs

Table of contents

HM-Java Basics-day02-Common APIs

1.API

1.1 API overview - use of help documents

1.2 Keyboard input string

2. String class

2.1 String overview

2.2 Construction method of String class

2.4 Comparison of differences in creating string objects

Interview question one:

2.5 Comparison of strings

2.6 User login case [Application]: compare the contents of strings, using the equals() method

2.7 Cases of traversing strings [Application]: public char charAt(int index): returns the char value at the specified index, and the index of the string also starts from 0

2.8 Counting the number of characters [Application]: public char[] toCharArray( ): Split the current string into a character array and return

2.9 Mobile phone number shielding-string interception: String substring(int beginIndex,int endIndex)

2.10 Sensitive word replacement-string replacement: String replace(CharSequence target, CharSequence replacement): Replace the target content in the current string with replacement and return a new string

2.11 Cutting Strings

2.12 String method summary

3 StringBuilder class

3.1 Overview of the StringBuilder class

3.2 Difference between StringBuilder class and String class

3.3 Construction method of StringBuilder class

3.4 Commonly used member methods of StringBuilder

3.5 Mutual conversion between StringBuilder and String 【Application】

3.6 StringBuilder splicing string case


HM-Java Basics-day02-Common APIs

1.API

1.1 API overview - use of help documents

  • What is an API

    API (Application Programming Interface): application programming interface

  • APIs in java

    Refers to the Java classes of various functions provided in the JDK. These classes encapsulate the underlying implementation. We don’t need to care about how these classes are implemented. We only need to learn how to use these classes. We can use the help documentation To learn how to use these APIs.

How to use the API help documentation:

  • Open the help document

  • Find the input box in the index tab

  • Enter Random in the input box

  • See which package the class is in

  • see class description

  • Look at the constructor

  • see member method

1.2 Keyboard input string

Scanner class:

next() : When a space is encountered, no more data will be entered, end tag: space, tab key

nextLine() : The data can be completely received, end mark: carriage return and line feed

Code :

package com.itheima.api;
import java.util.Scanner;
public class Demo1Scanner {
    /*
        next() : 遇到了空格, 就不再录入数据了
                结束标记: 空格, tab键
        nextLine() : 可以将数据完整的接收过来
                结束标记: 回车换行符
     */
    public static void main(String[] args) {
        // 1. 创建Scanner对象
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入:");
        // 2. 调用nextLine方法接收字符串
        // ctrl + alt + v : 快速生成方法的返回值
        String s = sc.nextLine();
        System.out.println(s);
    }
}
package com.itheima.api;
import java.util.Scanner;
public class Demo2Scanner {
    /*
        nextInt和nextLine方法配合使用的时候, nextLine方法就没有键盘录入的机会了
        建议: 今后键盘录入数据的时候, 如果是字符串和整数一起接受, 建议使用next方法接受字符串.
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入整数:");
        int num = sc.nextInt(); // 10 + 回车换行
        System.out.println("请输入字符串:");
        String s = sc.nextLine();
        System.out.println(num);
        System.out.println(s);
    }
}

2. String class

2.1 String overview

1 The String class is under the java.lang package, so there is no need to import the package when using it

2 The String class represents a string, and all string literals (such as "abc") in a Java program are implemented as instances of this class. That is to say, all double-quoted strings in a Java program are objects of the String class

3 Strings are immutable, their value cannot be changed after creation

2.2 Construction method of String class

Commonly used construction methods

sample code

package com.itheima.string;
public class Demo2StringConstructor {
    /*
        String类常见构造方法:
            public String() : 创建一个空白字符串对象,不含有任何内容
            public String(char[] chs) : 根据字符数组的内容,来创建字符串对象
            public String(String original) : 根据传入的字符串内容,来创建字符串对象
            String s = “abc”;  直接赋值的方式创建字符串对象,内容就是abc
         注意:
                String这个类比较特殊, 打印其对象名的时候, 不会出现内存地址
                而是该对象所记录的真实内容.
                面向对象-继承, Object类
     */
    public static void main(String[] args) {
        // public String() : 创建一个空白字符串对象,不含有任何内容
        String s1 = new String();
        System.out.println(s1);
        // public String(char[] chs) : 根据字符数组的内容,来创建字符串对象
        char[] chs = {'a','b','c'};
        String s2 = new String(chs);
        System.out.println(s2);
        // public String(String original) : 根据传入的字符串内容,来创建字符串对象
        String s3 = new String("123");
        System.out.println(s3);
    }
}

2.4 Comparison of differences in creating string objects

  • Created by constructor

    A string object created by new will apply for a memory space every time new, although the content is the same, but the address value is different

  • Created by direct assignment

    As long as the character string given in the form of "" is the same (order and case), no matter how many times it appears in the program code, the JVM will only create a String object and maintain it in the string pool

 String features:

Interview question one:

 answer:

 Interview question two:

answer:

 

2.5 Comparison of strings

2.5.1 String Comparison

  • == Comparing basic data types: comparing specific values

  • == Compare reference data types: compare object address values

String class: public boolean equals(String s) compares whether the content of two strings is the same, case-sensitive

code :

package com.itheima.stringmethod;
public class Demo1Equals {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "ABC";
        String s3 = "abc";
        // equals : 比较字符串内容, 区分大小写
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
        // equalsIgnoreCase : 比较字符串内容, 忽略大小写
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}

2.6 User login case [Application]: compare the contents of strings, using the equals() method

Case requirements:

If the user name and password are known, please use the program to realize the simulated user login. A total of three chances are given, after logging in, a corresponding prompt is given

Implementation steps:

  1. If the user name and password are known, just define two string representations

  2. Enter the user name and password to log in with the keyboard, and use Scanner to realize

  3. Compare the user name and password entered by the keyboard with the known user name and password, and give corresponding prompts.

  4. String content comparison, implemented with the equals() method

  5. Use a loop to realize multiple opportunities, the number of times here is clear, use a for loop to achieve, and use break to end the loop when the login is successful

Code :

package com.itheima.test;
import java.util.Scanner;
public class Test1 {
    /*
        需求:已知用户名和密码,请用程序实现模拟用户登录。
              总共给三次机会,登录之后,给出相应的提示
        思路:
        1. 已知用户名和密码,定义两个字符串表示即可
        2. 键盘录入要登录的用户名和密码,用 Scanner 实现
        3. 拿键盘录入的用户名、密码和已知的用户名、密码进行比较,给出相应的提示。
            字符串的内容比较,用equals() 方法实现
        4. 用循环实现多次机会,这里的次数明确,采用for循环实现,并在登录成功的时候,使用break结束循环
     */
    public static void main(String[] args) {
        // 1. 已知用户名和密码,定义两个字符串表示即可
        String username = "admin";
        String password = "123456";
        // 2. 键盘录入要登录的用户名和密码,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        // 4. 用循环实现多次机会,这里的次数明确,采用for循环实现
        for(int i = 1; i <= 3; i++){
            System.out.println("请输入用户名:");
            String scUsername = sc.nextLine();
            System.out.println("请输入密码:");
            String scPassword = sc.nextLine();
            // 3. 拿键盘录入的用户名、密码和已知的用户名、密码进行比较,给出相应的提示。
            if(username.equals(scUsername) && password.equals(scPassword)){
                System.out.println("登录成功");
                break;
            }else{
                if(i == 3){
                    System.out.println("您的登录次数已达到今日上限, 请明天再来");
                }else{
                    System.out.println("登录失败,您还剩余" + (3-i) +"次机会");
                }
            }
        }
    }
}

2.7 Cases of traversing strings [Application]: public char charAt(int index): returns the char value at the specified index, and the index of the string also starts from 0

Case requirements:

Enter a string with the keyboard, and use the program to traverse the string in the console

Implementation steps:

  1. Enter a character string with the keyboard and implement it with Scanner

  2. To traverse a string, you must first be able to get each character in the string, public char charAt(int index): returns the char value at the specified index, and the index of the string also starts from 0

  3. Traverse the string, secondly, get the length of the string, public int length(): return the length of this string

  4. traverse print

Code :

package com.itheima.test;
import java.util.Scanner;
public class Test2 {
    /*
        需求:键盘录入一个字符串,使用程序实现在控制台遍历该字符串
        思路:
        1. 键盘录入一个字符串,用 Scanner 实现
        2. 遍历字符串,首先要能够获取到字符串中的每一个字符
            public char charAt(int index):返回指定索引处的char值,字符串的索引也是从0开始的
        3. 遍历字符串,其次要能够获取到字符串的长度
            public int length():返回此字符串的长度
        4. 遍历打印
9
     */
    public static void main(String[] args) {
        //  1. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入:");
        String s = sc.nextLine();
        // 2. 遍历字符串,首先要能够获取到字符串中的每一个字符
        for(int i = 0; i < s.length(); i++){
            // i : 字符串的每一个索引
            char c = s.charAt(i);
            System.out.println(c);
        }
    }
}

2.8 Counting the number of characters [Application]: public char[] toCharArray( ): Split the current string into a character array and return

Case requirements:

Enter a string with the keyboard, and use the program to traverse the string in the console

Implementation steps:

  1. Enter a character string with the keyboard and implement it with Scanner

  2. Split the string into a character array, public char[] toCharArray( ): split the current string into a character array and return

  3. number of characters to traverse

Code :

package com.itheima.test;
import java.util.Scanner;
public class Test3 {
    /*
       需求:键盘录入一个字符串,使用程序实现在控制台遍历该字符串
       思路:
       1. 键盘录入一个字符串,用 Scanner 实现
       2. 将字符串拆分为字符数组
                public char[] toCharArray( ):将当前字符串拆分为字符数组并返回
       3. 遍历字符数组
    */
    public static void main(String[] args) {
        //  1. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入:");
        String s = sc.nextLine();
        // 2. 将字符串拆分为字符数组
        char[] chars = s.toCharArray();
        // 3. 遍历字符数组
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
    }
}

2.9 Mobile phone number shielding-string interception: String substring(int beginIndex,int endIndex)

String substring(int beginIndex) Intercept backward from the input index position until the end, get a new string and return
String substring(int beginIndex,int endIndex) Intercept from the beginIndex index position to the endIndex index position , get a new string and return, including the head, not including the tail

Case requirements:

Accept a mobile phone number from the keyboard in the form of a string, and mask the middle four digits. The final result is: 1561234

Implementation steps:

  1. Enter a character string with the keyboard and implement it with Scanner

  2. Extract the first three digits of a string

  3. Extract the last four digits of the string

  4. The two intercepted strings are added in the middle for splicing, and the result is output

Code :

package com.itheima.test;
import java.util.Scanner;
public class Test5 {
    /*
        需求:以字符串的形式从键盘接受一个手机号,将中间四位号码屏蔽
        最终效果为:156****1234
        思路:
        1. 键盘录入一个字符串,用 Scanner 实现
        2. 截取字符串前三位
        3. 截取字符串后四位
        4. 将截取后的两个字符串,中间加上****进行拼接,输出结果

        截取字符串:
        String substring(int beginIndex) 从传入的索引位置处,向后截取,一直截取到末尾,得到新的字符串并返回
        String substring(int beginIndex,int endIndex) 从beginIndex索引位置开始,截取到endIndex索引位置,得到新的字符串并返回,包含头,不包含尾
     */
    public static void main(String[] args) {
        // 1. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入手机号:");
        String telString = sc.nextLine();
        // 2. 截取字符串前三位
        String start = telString.substring(0,3);
        // 3. 截取字符串后四位
        String end = telString.substring(7);
        // 4. 将截取后的两个字符串,中间加上****进行拼接,输出结果
        System.out.println(start + "****" + end);
    }
}

2.10 Sensitive word replacement-string replacement: String replace(CharSequence target, CharSequence replacement): Replace the target content in the current string with replacement and return a new string

Case requirements:

Enter a string by keyboard, if the string contains (TMD), replace it with ***

Implementation steps:

  1. Enter a character string with the keyboard and implement it with Scanner

  2. Replace sensitive words String replace(CharSequence target, CharSequence replacement) Replace the target content in the current string with replacement and return a new string

  3. output result

Code :

package com.itheima.test;
import java.util.Scanner;
public class Test6 {
    /*
        需求:键盘录入一个 字符串,如果字符串中包含(TMD),则使用***替换
        思路:
        1. 键盘录入一个字符串,用 Scanner 实现
        2. 替换敏感词
                String replace(CharSequence target, CharSequence replacement)
                将当前字符串中的target内容,使用replacement进行替换,返回新的字符串
        3. 输出结果
     */
    public static void main(String[] args) {
        // 1. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入:");
        String s = sc.nextLine();
        // 2. 替换敏感词
        String result = s.replace("TMD","***");
        // 3. 输出结果
        System.out.println(result);
    }
}

2.11 Cutting Strings

Case requirements:

Enter student information from the keyboard in the form of character strings, for example: "Zhang San, 23"

Cut out valid data from the string and encapsulate it as a Student student object

Implementation steps:

  1. Write a Student class for encapsulating data

  2. Enter a character string with the keyboard and implement it with Scanner

  3. Cut the string according to the comma, get (Zhang San) (23)

    String[] split(String regex) : Cut according to the incoming string as a rule, store the cut content in the string array, and return the string array

  4. Take out the element content from the obtained string array, and encapsulate it as an object through the parameterized construction method of the Student class

  5. Call the getXxx method of the object to take out the data and print it.

Code :

package com.itheima.test;
import com.itheima.domain.Student;
import java.util.Scanner;
public class Test7 {
    /*
         需求:以字符串的形式从键盘录入学生信息,例如:“张三 , 23”
                从该字符串中切割出有效数据,封装为Student学生对象
         思路:
            1. 编写Student类,用于封装数据
            2. 键盘录入一个字符串,用 Scanner 实现
            3. 根据逗号切割字符串,得到(张三)(23)
                    String[] split(String regex) :根据传入的字符串作为规则进行切割
                    将切割后的内容存入字符串数组中,并将字符串数组返回
            4. 从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
            5. 调用对象getXxx方法,取出数据并打印。
     */
    public static void main(String[] args) {
        // 2. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生信息:");
        String stuInfo = sc.nextLine();
        // stuInfo = "张三,23";
        // 3. 根据逗号切割字符串,得到(张三)(23)
        String[] sArr = stuInfo.split(",");
//        System.out.println(sArr[0]);
//        System.out.println(sArr[1]);
        // 4. 从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
        Student stu = new Student(sArr[0],sArr[1]);
        // 5. 调用对象getXxx方法,取出数据并打印。
        System.out.println(stu.getName() + "..." + stu.getAge());
    }
}

2.12 String method summary

Common methods of the String class:

public boolean equals(Object anObject) compares the contents of strings, strictly case-sensitive

public boolean equalsIgnoreCase(String anotherString) compares the contents of strings, ignoring case

public int length() returns the length of this string

public char charAt(int index) returns the char value at the specified index

public char[] toCharArray() Returns after splitting the string into a character array

public String substring(int beginIndex, int endIndex) Intercept according to the start and end indexes to get a new string (including the head, not including the tail)

public String substring(int beginIndex) Intercept from the index passed in, and intercept to the end to get a new string

public String replace(CharSequence target, CharSequence replacement) Use the new value to replace the old value in the string to get a new string

public String[] split(String regex) Cut the string according to the incoming rules to get a string array

3 StringBuilder class

3.1 Overview of the StringBuilder class

Overview: StringBuilder is a variable string class. We can regard it as a container. The variable here means that the content in the StringBuilder object is variable

3.2 Difference between StringBuilder class and String class

  • String class: the content is immutable

  • StringBuilder class: the content is mutable

3.3 Construction method of StringBuilder class

Commonly used construction methods

method name illustrate
public StringBuilder() Creates an empty mutable string object with no content
public StringBuilder(String str) Create mutable string objects based on the contents of the string

sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //public StringBuilder():创建一个空白可变字符串对象,不含有任何内容
        StringBuilder sb = new StringBuilder();
        System.out.println("sb:" + sb);
        System.out.println("sb.length():" + sb.length());
        //public StringBuilder(String str):根据字符串的内容,来创建可变字符串对象
        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());
    }
}

3.4 Commonly used member methods of StringBuilder

  • Add and reverse methods

    method name illustrate
    public StringBuilder append (any type) Add data and return the object itself
    public StringBuilder reverse() returns the reverse character sequence
  • sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //创建对象
        StringBuilder sb = new StringBuilder();
        //public StringBuilder append(任意类型):添加数据,并返回对象本身
//        StringBuilder sb2 = sb.append("hello");
//
//        System.out.println("sb:" + sb);
//        System.out.println("sb2:" + sb2);
//        System.out.println(sb == sb2);
//        sb.append("hello");
//        sb.append("world");
//        sb.append("java");
//        sb.append(100);
        //链式编程
        sb.append("hello").append("world").append("java").append(100);
        System.out.println("sb:" + sb);
        //public StringBuilder reverse():返回相反的字符序列
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

3.5 Mutual conversion between StringBuilder and String 【Application】

StringBuilder to String

public String toString(): Convert StringBuilder to String through toString()

String to StringBuilder

public StringBuilder(String s): Convert String to StringBuilder through the construction method


//示例代码

public class StringBuilderDemo02 {
    public static void main(String[] args) {
        /*
        //StringBuilder 转换为 String
        StringBuilder sb = new StringBuilder();
        sb.append("hello");
        //String s = sb; //这个是错误的做法
        //public String toString():通过 toString() 就可以实现把 StringBuilder 转换为 String
        String s = sb.toString();
        System.out.println(s);
        */
        //String 转换为 StringBuilder
        String s = "hello";
        //StringBuilder sb = s; //这个是错误的做法
        //public StringBuilder(String s):通过构造方法就可以实现把 String 转换为 StringBuilder
        StringBuilder sb = new StringBuilder(s);
        System.out.println(sb);
    }
}

3.6 StringBuilder splicing string case

Case requirements:

Define a method to splice the data in the int array into a string according to the specified format and return it, call this method,

And output the result on the console. For example, the array is int[] arr = {1,2,3}; , the output after executing the method is: [1, 2, 3]

Implementation steps:

  1. Define an array of int type, and complete the initialization of the array elements with static initialization

  2. Define a method for splicing the data in the int array into a string according to the specified format and returning it. Return value type String, parameter list int[] arr

  3. In the method, use StringBuilder to splicing according to the requirements, and convert the result into String and return

  4. Call the method and receive the result in a variable

  5. output result

Code :

/*
    思路:
        1:定义一个 int 类型的数组,用静态初始化完成数组元素的初始化
        2:定义一个方法,用于把 int 数组中的数据按照指定格式拼接成一个字符串返回。
          返回值类型 String,参数列表 int[] arr
        3:在方法中用 StringBuilder 按照要求进行拼接,并把结果转成 String 返回
        4:调用方法,用一个变量接收结果
        5:输出结果
 */
public class StringBuilderTest01 {
    public static void main(String[] args) {
        //定义一个 int 类型的数组,用静态初始化完成数组元素的初始化
        int[] arr = {1, 2, 3};
        //调用方法,用一个变量接收结果
        String s = arrayToString(arr);
        //输出结果
        System.out.println("s:" + s);
    }
    //定义一个方法,用于把 int 数组中的数据按照指定格式拼接成一个字符串返回
    /*
        两个明确:
            返回值类型:String
            参数:int[] arr
     */
    public static String arrayToString(int[] arr) {
        //在方法中用 StringBuilder 按照要求进行拼接,并把结果转成 String 返回
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i=0; i<arr.length; i++) {
            if(i == arr.length-1) {
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(", ");
            }
        }
        sb.append("]");
        String s = sb.toString();
        return  s;
    }
}

Guess you like

Origin blog.csdn.net/qq_53663718/article/details/127281689