[Java hodgepodge] string inversion, custom sorting, registration problems, data type statistics


dy brushed ten videos and five videos about strings, sorting and related interview questions. I was shocked to write this article and review sorting and algorithms again
At the beginning of the game, I was tortured by an inverted specified string. I don't want to go back to the past

String inversion( 🏁)

Scenario: the user enters a string of characters and reverses the corresponding characters according to the instructions entered by the user

1. write a static method that can accept the string passed in by the user and the inverted interval
2. judge the input content (if)
3. convert the string entered by the user into a char[] array (why char? Because the smallest element of the string is a character)
4. use a for loop to traverse the array and pass in two variables, one beginning and one end. The process of the for loop is abstracted into the form from two ends to the middle. In this process, the purpose of exchanging two elements at different positions is achieved

5. exception handling ensures the robustness of the program (throw a running exception before reaching the if condition), and receive and handle exceptions in the main function**

public class String01 {
    public static void main(String[] args) {
        System.out.println("=====Before reversal=====");
        String str = "abcdefg";
        System.out.println("=====After reversal=====");
        try {
            str = method(str, 2, 6);
        } catch (Exception e) {
    public static String method(String str, int n1, int n2) {
        //Make a verification
        //Important skills - write the correct situation first and then reverse it!!!!!!!!!!!!!!!!!!!!!!!!!!!
        if (!(str != null&& n1>=0&&n1>n2&&n2<str.length())) {
            throw new RuntimeException("parameter is incorrect");
            char[] chars = str.toCharArray();
            char temp = ' ';
            for (int i = n1, j = n2; i < j; i++, j--) {
                temp = chars[i];
                chars[i] = chars[j];
                chars[j] = temp;
            return new String(chars);

Custom sorting( 🚩)

Scene: free switching from large to small and from small to large

1. write a static method for bubble sorting. You can pass the array to be compared and the Comparator object to the formal parameter
2. use anonymous inner classes to implement Comparator interface to achieve customized functions
3. take the result returned by the Comparator object as the condition for sorting
4. exception handling

public class ArraysTest {
    public static void main(String[] args) {
        int[] arr = {1, -9, 8, 55, 4};
bubble01(arr, new Comparator() {
    public int compare(Object o1, Object o2) {
        int i1= (Integer) o1;
        int i2= (Integer) o2;
        return i1- i2;  // return i2- i1;
    public static void bubble01(int[] arr, Comparator c) {   //After the arrangement, it is still an array
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                //The value of array sorting is determined by the value returned by c.compare(arr[j],arr[j+1])
                if (c.compare(arr[j],arr[j+1])>0) {  //from small to large
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;

Registration questions( 🏁)

Scenario: enter the user name, password, and email address. If the information is entered correctly, you will be prompted that the registration is successful. Otherwise, an exception object will be generated. Requirements:
1. the user name is 2 or 3 or 4 in length
2. the length of the password is 6, and all numbers are required
3. the mailbox contains @ and And @ at In front of

1. the main premise is that the input is not blank
2. the user name length is achieved by comparing the string length
3. two boolean methods are used to distinguish passwords and mailboxes (return true\false and combine if to compare directly)
4. the mailbox format can be realized by comparing the specified character subscripts in the string
5. exception handling

  public static void main(String[] args) {
        String name = "pyq";
        String ps = "123456";
        String em = "123@qq.com";
        try { //Try catch maintainer receiving exception
            check(name, ps, em);
            System.out.println("Congratulations on your successful registration!");
        } catch (Exception e) {  //Receive the exceptions that may be thrown in the check method and output the abnormal termination program
    public static void check(String userName, String passWord, String email) {
        if (!(userName != null && passWord != null && email != null)) {
            throw new RuntimeException("Cannot enter blank~~~");
        int ul = userName.length();
        int pl = passWord.length();
        if (!(ul >= 2 && ul <= 4)) {   //Username length is 2 or 3 or 4
            throw new RuntimeException("The user name you entered is incorrect~");  //Unqualified - throw an exception
        if (!(isDigtal(passWord) && pl == 6)) {//The length of the password is 6. It is required to be all digital isDigital
            throw new RuntimeException("The password you entered is incorrect~");
        if (!(eCheck(email))) {  //Mailbox contains @ and And @ at In front of
            throw new RuntimeException("The email format you entered is incorrect~");
    public static boolean isDigtal(String password) {  //This method is used to determine whether the entered passwords are all numbers
        char[] m1 = password.toCharArray();//By converting the input string password into a character array, traversal and comparison to determine
        for (int i = 0; i < m1.length; i++) {
            if (m1[i] < '0' || m1[i] > '9') {
                return false;
        return true;
    public static boolean eCheck(String email) { //This method is used to determine the @ and problem
        int i = email.indexOf("@");   //The function is realized by obtaining the subscript of the string and comparing it
        int j = email.indexOf(".");
        if (!(i < j && i >= 0)) {
            return false;
        return true;

Data type statistics

Scenario: user input to determine the number of upper case letters, lower case letters and numbers in the string

1. convert string to char[] character array
2. traverse the array and compare with '0', '9', 'a', 'Z', 'a', 'Z'
3. exception handling

public class homework03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter a string~");
        String eg=scanner.next();
    public static void printName(String str) {
        if (str == null) {
            System.out.println("Do not leave blank!");
        int sL = str.length();
        int numCount = 0;  //Variables for counting
        int lowerCount = 0;
        int upperCount = 0;
        char[] m1 = str.toCharArray();
        //The old routine converts the input string into a character array and performs logical judgment through traversal to realize the function
        for (int i = 0; i < sL; i++) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            } else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
            } else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'z') {
        System.out.println("Number yes:" + numCount + "\n Lower case letters have:" +
                lowerCount + "\n Capital letters have:" + upperCount);

Ps: this anonymous inner class is really hard to use
How's the cooking? Is the chowder good?

Tags: Java Algorithm data structure JavaSE programming language

Posted by My220x on Fri, 03 Jun 2022 23:24:51 +0530