Object oriented exercise 2 and API usage

Posted by MCrosbie on Sun, 03 Oct 2021 23:38:09 +0200

package com.atguigu.exer;

public class Person {
    private int age;
    public void setAge(int a){
        if (a<0||a>130){
            System.out.println("Illegal incoming data");
            return;
        }
            age=a;
        }
    public int  getAge(){
        return age;
    }

}

Test class

package com.atguigu.exer;

public class PersonTest {
    public static void main(String[] args) {
        Person p1=new Person();
        p1.setAge(89);

        System.out.println("Age:"+p1.getAge());
    }
}

2. Write two classes, TriAngle and TriAngleTest
The TriAngle class declares the private bottom edge length base and high H eight, and declares the public method to access the private variable. In addition, provide the necessary constructors for the class. Another class uses these common methods to calculate the area of a TriAngle

package com.atguigu.exer;

public class TriAngle {
    private double base;
    private double height;

    public TriAngle(){

    }
    public TriAngle(double b,double h ){
        base =b;
        height =h;
    }

    public void setBase(double b){
        base=b;
    }
    public double getBase(){
        return base;
    }
    public void setHeight(double h){
        height =h;
    }
    public double getHeight(){
        return height;
    }
}

package com.atguigu.exer;

public class TriAngleTest {
    public static void main(String[] args) {
        TriAngle t1=new TriAngle();//Call the null argument constructor
        t1.setBase(3.1);
        t1.setHeight(5.56);

        System.out.println("base:"+t1.getBase()+"," +
                "height:"+t1.getHeight());
        System.out.println("*************");
        TriAngle t2=new TriAngle(2.5,6);//Calling a constructor with parameters


    }
}

Exercise 1

Write a class called Account to simulate the Account. The properties and methods of this class are shown in the following figure.
The class includes the following attributes:
Account id, balance and annual interest rate; Included methods: accessor methods (getter and setter methods), withdrawal method withraw(), deposit method deposit().
Account
private int id
private double balance
private double annualInterestRate
public Account (int id, double balance, double annualInterestRate )
public int getId()
public double getBalance()
public double getAnnualInterestRate()
public void setId( int id)
public void setBalance(double balance)
public void setAnnualInterestRate(double annualInterestRate)
public void withdraw (double amount) / / withdraw money
public void deposit (double amount) / / deposit money
Tip: in the withdrawal method withdraw, you need to judge whether the user's balance can meet the withdrawal amount requirements. If not
If yes, prompt shall be given.
2. Create Customer class.
Customer
private String firstName
private String lastName
private Account account
public Customer(String f,String l)
public String getFirstName()
public String getLastName()
public Account getAccount()
public void setAccount(Account account)
a. Declare three private object properties: firstName, lastName, and account.
b. Declare a public constructor with two parameters (f and l) representing object properties
c. Declare two public accessors to access the object properties, and the methods getFirstName and getLastName return the corresponding properties
Sex.
d. Declare the setAccount method to assign a value to the account attribute.
e. Declare the getAccount method to get the account attribute.
3. Write a test program.
(1) Create a Customer named Jane Smith, who has an account number of 1000 and a balance of 2000 yuan,
Accounts with an annual interest rate of 1.23%.
(2) Operate on Jane Smith.
Deposit 100 yuan and withdraw 960 yuan. Take out another 2000 yuan.
Print out Jane Smith's basic information

package com.atguigu.exer;

public class Account {
    private int id;//account number
    private double balance;//balance
    private double annualInterestRate;//Annual interest rate

    //constructor 
    public Account (int id, double balance, double annualInterestRate ) {
        this.id = id;
        this.balance = balance;
        this.annualInterestRate=annualInterestRate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public double getAnnualInterestRate() {
        return annualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }
    //Withdraw money
    public void withdraw (double amount){
        if(balance<amount){
            System.out.println("Insufficient balance, withdrawal failed");
            return;
        }
        balance-=amount;
        System.out.println("Successfully removed"+amount);
    }

    //save money
    public void deposit (double amount){
        if(amount>0){
            balance+=amount;
            System.out.println("Successfully deposited"+amount);
        }
    }

}

package com.atguigu.exer;

public class Counter {
    private String firstName;
    private String lastName;
    private Account account;

    public Counter(String f, String l) {
        this.firstName = f;
        this.lastName = l;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }
}

**CustomerTest class**
package com.atguigu.exer;
/*Write a test program.
(1) Create a Customer named Jane Smith. He has an account number of 1000,
The balance is 2000 yuan,
Accounts with an annual interest rate of 1.23%.
(2) Operate on Jane Smith.
Deposit 100 yuan and withdraw 960 yuan. Take out another 2000 yuan.
Print out Jane Smith's basic information
 */

public class CustomerTest {
    public static void main(String[] args) {
        Counter cust=new Counter("jane","smith");

        Account acct=new Account(1000,2000,0.0123);

        cust.setAccount(acct);
        cust.getAccount().deposit(100);
        cust.getAccount().withdraw(960);
        cust.getAccount().withdraw(2000);

        System.out.println("Customer["+cust.getLastName()+","+
                cust.getFirstName()+"]has a account :id is"+
                cust.getAccount().getId()+","+"annualInterestRate is:"+
                cust.getAccount().getAnnualInterestRate()*100+"%,balance is"+cust.getAccount().getBalance());

    }
}

**Operation results**
Successfully deposited 100.0
 960 successfully removed.0
 Insufficient balance, withdrawal failed
Customer[smith,jane]has a account :id is1000,annualInterestRate is:1.23%,balance is1140.0

Process finished with exit code 0

1.API

1.1 API Overview - use of help documents

  • What is an API

    API (Application Programming Interface): application programming interface

  • API in java

    It refers to Java classes with 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 just need to learn how to use these classes. We can learn how to use these API s through help documents.

How to use API help documentation:

  • Open help document

  • Locate the input box in the index tab

  • Enter Random in the input box

  • See which package the class is in

  • Look at the description of the class

  • Look at the construction method

  • Look at member methods

1.2 keyboard input string

Scanner class:

next(): if a space is encountered, no more data will be entered. End tag: space, tab

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

Code implementation:

package com.itheima.api;

import java.util.Scanner;

public class Demo1Scanner {
    /*
        next() : If you encounter a space, you will no longer enter data

                End tag: space, tab

        nextLine() : The data can be received completely

                End tag: carriage return line feed
     */
    public static void main(String[] args) {
        // 1. Create Scanner object
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        // 2. Call the nextLine method to receive the string
        // ctrl + alt + v: return value of quick generation method
        String s = sc.nextLine();

        System.out.println(s);
    }
}

package com.itheima.api;

import java.util.Scanner;

public class Demo2Scanner {
    /*
        nextInt When used in conjunction with the nextLine method, the nextLine method has no chance of keyboard entry

        Suggestion: when entering data on the keyboard in the future, if the string and integer are accepted together, it is recommended to use the next method to accept the string
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("please enter an integer:");
        int num = sc.nextInt(); // 10 + enter line feed
        System.out.println("Please enter a string:");
        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. All String literals (such as "abc") in the Java program are implemented as instances of this class, that is, all double quoted strings in the Java program are objects of the String class

3 strings are immutable, and their values cannot be changed after creation

2.2 construction method of string class

Common construction methods

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wRX523nb-1633251143339)(.\img90939947722.png)]

Sample code

package com.itheima.string;

public class Demo2StringConstructor {
    /*
        String Common construction methods of class:

            public String() : Create a blank string object that contains nothing
            public String(char[] chs) : Create a string object based on the contents of the character array
            public String(String original) : Creates a string object based on the passed in string content
            String s = "abc";  Create a string object by direct assignment. The content is abc

         be careful:
                String This class is special. When printing its object name, there will be no memory address
                It is the real content recorded by the object

                Object oriented - inheritance, object class
     */
    public static void main(String[] args) {
        // public String(): create a blank string object without any content
        String s1 = new String();
        System.out.println(s1);

        // public String(char[] chs): creates a string object according to the contents of the character array
        char[] chs = {'a','b','c'};
        String s2 = new String(chs);
        System.out.println(s2);

        // public String(String original): creates a string object based on the incoming string content
        String s3 = new String("123");
        System.out.println(s3);
    }
}

2.4 comparison of differences in creating string objects

  • Create by construction method

    For string objects created through new, each new will apply for a memory space. Although the contents are the same, the address values are different

  • Create by direct assignment

    As long as the character sequence 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

2.5 string comparison

2.5.1 string comparison

  • ==Compare basic data types: specific values are compared
  • ==Compare reference data types: object address values are compared

String class: public boolean equals(String s) compares whether the contents of two strings are the same and 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: compares string contents, case sensitive
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));

        // equalsIgnoreCase: compares string contents, ignoring case
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}

2.6 user login case [application]

Case requirements:

Known user name and password, please use the program to simulate user login. Give a total of three opportunities. After logging in, give corresponding prompts

**Implementation steps:**

  1. If the user name and password are known, define two string representations
  2. Enter the user name and password to log in with the keyboard, which is implemented with Scanner
  3. Compare the user name and password entered on the keyboard with the known user name and password, and give the corresponding prompt.
  4. The content comparison of the string is implemented with the equals() method
  5. Use the loop to realize multiple opportunities. The number of times here is clear. Use the for loop to realize it. When the login is successful, use the break to end the loop

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test1 {
    /*
        Requirements: if the user name and password are known, please use the program to simulate user login.
              Give a total of three opportunities. After logging in, give corresponding prompts

        Idea:
        1. If the user name and password are known, define two string representations
        2. Enter the user name and password to log in with the keyboard, which is implemented with Scanner
        3. Compare the user name and password entered on the keyboard with the known user name and password, and give the corresponding prompt.
            The content comparison of the string is implemented with the equals() method
        4. Use the loop to realize multiple opportunities. The number of times here is clear. Use the for loop to realize it. When the login is successful, use break to end the loop

     */
    public static void main(String[] args) {
        // 1. If the user name and password are known, define two string representations
        String username = "admin";
        String password = "123456";
        // 2. Enter the user name and password to log in with the keyboard, which is implemented with Scanner
        Scanner sc = new Scanner(System.in);
        // 4. Use the loop to realize multiple opportunities. The number of times here is clear, and use the for loop to realize
        for(int i = 1; i <= 3; i++){
            System.out.println("enter one user name:");
            String scUsername = sc.nextLine();
            System.out.println("Please input a password:");
            String scPassword = sc.nextLine();
            // 3. Compare the user name and password entered on the keyboard with the known user name and password, and give the corresponding prompt.
            if(username.equals(scUsername) && password.equals(scPassword)){
                System.out.println("Login succeeded");
                break;
            }else{
                if(i == 3){
                    System.out.println("Your login times have reached today's limit, Please come back tomorrow");
                }else{
                    System.out.println("Login failed,You still have" + (3-i) +"Second chance");
                }

            }
        }

    }
}

2.7 traversal string case [ application ]

Case requirements:

Enter a string on the keyboard and use the program to traverse the string on the console

Implementation steps:

  1. Enter a string on the keyboard and implement it with Scanner
  2. To traverse a string, you must first be able to obtain each character in the string. public char charAt(int index): returns the char value at the specified index. The index of the string also starts from 0
  3. Traverse the string, and then get the length of the string. public int length(): returns the length of the string
  4. Traversal printing

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test2 {
    /*
        Requirements: enter a string on the keyboard and use the program to traverse the string on the console

        Idea:
        1. Enter a string on 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 starts from 0
        3. Traverse the string, and then get the length of the string
            public int length(): Returns the length of this string
        4. Traversal printing
9
     */
    public static void main(String[] args) {
        //  1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        String s = sc.nextLine();
        // 2. To traverse a string, you must first be able to get each character in the string
        for(int i = 0; i < s.length(); i++){
            // i: each index of the string
            char c = s.charAt(i);
            System.out.println(c);
        }
    }
}

2.8 case of counting the number of characters [ application ]

Case requirements:

Enter a string on the keyboard and use the program to traverse the string on the console

Implementation steps:

  1. Enter a string on the keyboard and implement it with Scanner
  2. Split the string into character arrays, public char[] toCharArray(): split the current string into character arrays and return
  3. Number of traversal characters

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test3 {
    /*
       Requirements: enter a string on the keyboard and use the program to traverse the string on the console

       Idea:
       1. Enter a string on the keyboard and implement it with Scanner
       2. Splits a string into an array of characters
                public char[] toCharArray( ): Splits the current string into an array of characters and returns
       3. Traversal character array

    */
    public static void main(String[] args) {
        //  1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        String s = sc.nextLine();
        // 2. Split the string into character arrays
        char[] chars = s.toCharArray();
        // 3. Traverse character array
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
    }
}

2.9 mobile phone number shielding - string interception

Case requirements:

Accept a mobile phone number from the keyboard in the form of string, and shield the middle four numbers
The final effect is: 156 * * * * 1234

Implementation steps:

  1. Enter a string on the keyboard and implement it with Scanner
  2. Intercept the first three digits of the string
  3. Intercept the last four digits of the string
  4. Splice the two intercepted strings with * * * * in the middle to output the result

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test5 {
    /*
        Requirement: accept a mobile phone number from the keyboard in the form of string, and shield the middle four numbers
        The final effect is: 156 * * * * 1234

        Idea:
        1. Enter a string on the keyboard and implement it with Scanner
        2. Intercept the first three digits of the string
        3. Intercept the last four digits of the string
        4. Splice the two intercepted strings with * * * * in the middle to output the result

     */
    public static void main(String[] args) {
        // 1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your mobile phone number:");
        String telString = sc.nextLine();
        // 2. Intercept the first three digits of the string
        String start = telString.substring(0,3);
        // 3. Intercept the last four digits of the string
        String end = telString.substring(7);
        // 4. Splice the two intercepted strings with * * * * in the middle to output the result
        System.out.println(start + "****" + end);
    }
}

2.10 sensitive word substitution - string substitution

Case requirements:

Enter a string on the keyboard. If the string contains (TMD), use * * * instead

Implementation steps:

  1. Enter a string on 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 to return a new string
  3. Output results

Code implementation:

package com.itheima.test;

import java.util.Scanner;

public class Test6 {
    /*
        Requirement: enter a string on the keyboard. If the string contains (TMD), use * * * instead

        Idea:
        1. Enter a string on 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 to return a new string
        3. Output results

     */
    public static void main(String[] args) {
        // 1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter:");
        String s = sc.nextLine();
        // 2. Replace sensitive words
        String result = s.replace("TMD","***");
        // 3. Output results
        System.out.println(result);
    }
}

2.11 cutting strings

Case requirements:

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

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

Implementation steps:

  1. Write the Student class to encapsulate the data

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

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

    String[] split(String regex): cut according to the incoming string as a rule
    Store the cut content into the string array and return the string array

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

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

Code implementation:

package com.itheima.test;

import com.itheima.domain.Student;

import java.util.Scanner;

public class Test7 {
    /*
         Requirement: input student information from the keyboard in the form of string, for example: "Zhang San, 23"
                Cut the valid data from the string and encapsulate it as a Student object
         Idea:
            1. Write the Student class to encapsulate the data
            2. Enter a string on the keyboard and implement it with Scanner
            3. Cut the string according to the comma to get (Zhang San) (23)
                    String[] split(String regex) : Cut according to the incoming string as a rule
                    Store the cut content into the string array and return the string array
            4. Take the element content from the obtained string array and encapsulate it as an object through the parametric construction method of Student class
            5. Call the getXxx method of the object, take out the data and print it.

     */
    public static void main(String[] args) {
        // 2. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter student information:");
        String stuInfo = sc.nextLine();
        // stuInfo = "Zhang San, 23";
        // 3. Cut the string according to the comma to get (Zhang San) (23)
        String[] sArr = stuInfo.split(",");

//        System.out.println(sArr[0]);
//        System.out.println(sArr[1]);

        // 4. Take the element content from the obtained string array and encapsulate it as an object through the parametric construction method of Student class
        Student stu = new Student(sArr[0],sArr[1]);

        // 5. Call the getXxx method of the object, take out the data and print it.
        System.out.println(stu.getName() + "..." + stu.getAge());
    }
}

2.12 summary of string method

Common methods of String class:

public boolean equals(Object anObject) compares the contents of strings and is strictly case sensitive

Public Boolean equalsignorecase (string otherstring) 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() splits the string into character arrays and returns

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

public String substring(int beginIndex) is intercepted from the incoming index to the end to get a new string

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

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

3 StringBuilder class

3.1 overview of 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 differences between StringBuilder class and String class

  • **String class: * * the content is immutable
  • **StringBuilder class: * * the content is variable

3.3 construction method of StringBuilder class

Common construction methods

Method nameexplain
public StringBuilder()Create a blank variable string object that contains nothing
public StringBuilder(String str)Creates a variable string object based on the contents of the string

Sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //public StringBuilder(): creates a blank variable string object without any content
        StringBuilder sb = new StringBuilder();
        System.out.println("sb:" + sb);
        System.out.println("sb.length():" + sb.length());

        //public StringBuilder(String str): creates a variable string object according to the contents of the string
        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());
    }
}

3.4 common member methods of StringBuilder

  • Add and reverse methods

    Method nameexplain
    Public StringBuilder append (any type)Add data and return the object itself
    public StringBuilder reverse()Returns the opposite sequence of characters
  • Sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //create object
        StringBuilder sb = new StringBuilder();

        //Public StringBuilder append (any type): adds data and returns the object itself
//        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);

        //Chain programming
        sb.append("hello").append("world").append("java").append(100);

        System.out.println("sb:" + sb);

        //public StringBuilder reverse(): returns the opposite character sequence
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

3.5 conversion between StringBuilder and String [ application ]

  • Convert StringBuilder to String

    public String toString(): you can convert StringBuilder to String through toString()

  • Convert String to StringBuilder

    public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a method

  • Sample code

public class StringBuilderDemo02 {
    public static void main(String[] args) {
        /*
        //StringBuilder Convert to String
        StringBuilder sb = new StringBuilder();
        sb.append("hello");

        //String s = sb; //This is wrong

        //public String toString(): You can convert StringBuilder to String by toString()
        String s = sb.toString();
        System.out.println(s);
        */

        //Convert String to StringBuilder
        String s = "hello";

        //StringBuilder sb = s; // This is wrong

        //public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a method
        StringBuilder sb = new StringBuilder(s);

        System.out.println(sb);
    }
}

3.6 StringBuilder splicing string cases

Case requirements:

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

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

Implementation steps:

  1. Define an array of type int, and use static initialization to complete the initialization of array elements
  2. Defines a method for splicing the data in the int array into a string according to the specified format.
    Return value type String, parameter list int[] arr
  3. In the method, use StringBuilder to splice as required, and convert the result into String to return
  4. Call the method to receive the result with a variable
  5. Output results

Code implementation:

/*
    Idea:
        1:Define an array of type int, and use static initialization to complete the initialization of array elements
        2:Defines a method for splicing the data in the int array into a string according to the specified format.
          Return value type String, parameter list int[] arr
        3:In the method, use StringBuilder to splice as required, and convert the result into String to return
        4:Call the method to receive the result with a variable
        5:Output results
 */
public class StringBuilderTest01 {
    public static void main(String[] args) {
        //Define an array of type int, and use static initialization to complete the initialization of array elements
        int[] arr = {1, 2, 3};

        //Call the method to receive the result with a variable
        String s = arrayToString(arr);

        //Output results
        System.out.println("s:" + s);

    }

    //Defines a method for splicing the data in the int array into a string according to the specified format
    /*
        Two clear:
            Return value type: String
            Parameter: int[] arr
     */
    public static String arrayToString(int[] arr) {
        //In the method, use StringBuilder to splice as required, and convert the result into String to return
        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;
    }
}
rayToString(arr);

        //Output results
        System.out.println("s:" + s);

    }

    //Defines a method for splicing the data in the int array into a string according to the specified format
    /*
        Two clear:
            Return value type: String
            Parameter: int[] arr
     */
    public static String arrayToString(int[] arr) {
        //In the method, use StringBuilder to splice as required, and convert the result into String to return
        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;
    }
}

Topics: Java