Java Review Notes - Methods


insert image description here

First, the definition of the method

In Java, a method is an independent block of code that performs a specific task or operation. Methods can accept input parameters and return a value, or they can accept no parameters or return no value.

The method consists of the following components:

  1. Method signature: The combination of the name of the method and the parameter list, which is used to uniquely identify a method. Method signature includes method name and parameter types, for example: methodName(parameterType1 parameter1, parameterType2 parameter2, ...).

  2. Method body: A method body is a block of code contained in a method that implements a specific function or logic. The code in the method body will be executed in order.

  3. Parameter list: A method can accept zero or more parameters, which are the values ​​passed to the method when the method is executed. Each parameter includes parameter type and parameter name, separated by commas.

  4. Return Type: A method may or may not return a value. The return type specifies the type of data returned by the method. If the method does not return any value, the return type is void.

The method definition format is as follows:

修饰符 返回类型 方法名(参数列表) {
    // 方法体
}

in:

  • Modifiers (optional): Used to specify the visibility and access rights of the method, such as public, privateetc.
  • Return type: Specifies the data type returned by the method, if the method does not return any value, the return type is void.
  • Method name: The name of the method, used to call the method in the code.
  • Parameter list (optional): Specifies the parameter types and parameter names accepted by the method.
  • Method body: the code block contained in the method to achieve specific functions.

By defining methods, the code can be decomposed into smaller maintainable and reusable modules, improving the readability and maintainability of the code.

Second, the simplest method definition and call

The simplest method definition and invocation can be performed in the following steps:

  1. Method Definition: First, define a method in the class. Methods can be defined anywhere in the class, but are usually placed at the outermost level of the class.
public class MyClass {
    
    
    // 方法定义
    public void myMethod() {
    
    
        // 方法体
        System.out.println("Hello, World!");
    }
}

The above code defines a myMethodmethod called with no parameters and a return type of void, which prints "Hello, World!" in the method body.

  1. Method call: Where a method needs to be called, use the name of the method followed by a pair of parentheses to call the method.
public class MyClass {
    
    
    // 方法定义
    public void myMethod() {
    
    
        // 方法体
        System.out.println("Hello, World!");
    }

    public static void main(String[] args) {
    
    
        // 方法调用
        MyClass obj = new MyClass();
        obj.myMethod(); // 调用 myMethod 方法
    }
}

In the code above, we maincreated a MyClassobject in the method obj, and then obj.myMethod()called myMethodthe method via .

Running the above code, the output is "Hello, World!".

Three, method definition and call with parameters

Method definition and invocation with parameters can be performed in the following steps:

  1. Method definition: Parameters are defined within the parentheses of the method. Parameters can be any legal Java data type, and there can be multiple parameters, separated by commas.
public class MyClass {
    
    
    // 带参数的方法定义
    public void myMethod(String name, int age) {
    
    
        // 方法体
        System.out.println("Hello, " + name + "! You are " + age + " years old.");
    }
}

The above code defines a myMethodmethod named , which accepts a Stringparameter of type nameand a intparameter of type age, and prints out a string with parameter information in the method body.

  1. Method call: When calling a method, pass in the corresponding parameter value. The number, order, and types of actual parameters must match the formal parameters in the method definition.
public class MyClass {
    
    
    // 带参数的方法定义
    public void myMethod(String name, int age) {
    
    
        // 方法体
        System.out.println("Hello, " + name + "! You are " + age + " years old.");
    }

    public static void main(String[] args) {
    
    
        // 方法调用
        MyClass obj = new MyClass();
        obj.myMethod("Alice", 25); // 调用 myMethod 方法并传入参数值
    }
}

In the above code, we maincreated an MyClassobject in the method obj, then obj.myMethod("Alice", 25)called myMethodthe method through and passed in a Stringparameter of type "Alice"and a intparameter of type 25.

Running the above code, the output is "Hello, Alice! You are 25 years old.".

Fourth, the definition and call of methods with return values

Method definition and invocation with a return value can be performed in the following steps:

  1. Method definition: Prepend the return type of the method with the return type. The return type can be any legal Java data type, including primitive data types and reference data types.
public class MyClass {
    
    
    // 带返回值的方法定义
    public int add(int a, int b) {
    
    
        // 方法体
        int sum = a + b;
        return sum;
    }
}

The above code defines a addmethod called that accepts two intparameters of type aand bcalculates their sum in the method body and returns the result as the return value.

  1. Method call: When calling a method, a variable can be used to receive the return value of the method.
public class MyClass {
    
    
    // 带返回值的方法定义
    public int add(int a, int b) {
    
    
        // 方法体
        int sum = a + b;
        return sum;
    }

    public static void main(String[] args) {
    
    
        // 方法调用
        MyClass obj = new MyClass();
        int result = obj.add(5, 3); // 调用 add 方法并接收返回值
        System.out.println("The sum is: " + result);
    }
}

In the above code, we maincreated a MyClassobject in the method obj, then obj.add(5, 3)called addthe method through and assigned the return value to a variable resultof inttype called . Finally, we System.out.printlnprint out the result using .

Running the above code, the output is "The sum is: 8".

Five, summary

To summarize the main points of the Java method:

  1. A method is a reusable block of code that accomplishes a specific task.
  2. A method can accept input parameters and can have a return value.
  3. A method definition includes the method's access modifiers, return type, method name, parameter list, and method body.
  4. A method's access modifier can be public, protected, private, or default (no modifier).
  5. The return type specifies the return value type after the method is executed, which can be a basic data type or a reference data type.
  6. Method names should be descriptive and follow naming conventions for code readability.
  7. The parameter list specifies the types and names of the input parameters accepted by the method.
  8. The method body is the concrete implementation of the method, which contains the code logic to be executed.
  9. Methods can have return statements to return a value, and the type of the return value must match the method's return type.
  10. Methods can be called by other methods by calling the method name and parameter list.
  11. Method calls can be made in the same class or in different classes, using the object name or class name to call the method.
  12. Methods can be overloaded, that is, there can be multiple methods with the same name but different parameter lists in the same class.
  13. Methods can be overridden, that is, subclasses can override methods in the parent class to achieve different functions.

The above are some key points about Java methods. After mastering these contents, you can skillfully define and use methods to complete various tasks.

Six, method overloading

Java method overloading means that in the same class, multiple methods with the same name but different parameter lists can be defined. Method overloading can be distinguished by the number, type, or order of parameters.

Overloaded methods have the following characteristics:

  1. Same method name: Overloaded methods must have the same method name.

  2. Different parameter lists: The parameter lists of overloaded methods must be different, which can be different numbers of parameters, different parameter types, or different order of parameters.

  3. Return types can be the same or different: Overloaded methods can have the same return type or different return types.

  4. Access modifiers can be the same or different: Overloaded methods can have the same access modifiers or different access modifiers.

  5. Overloaded methods can throw the same or different exceptions: Overloaded methods can declare the same exception or different exceptions.

Overloaded methods are used to implement similar functions but different parameters, improving code reusability and readability. When calling an overloaded method, the compiler will determine which method to call based on the type of parameters actually passed in. If no matching method is found, it will compile with an error.

For example, here is an example that calculates the addition of two numbers:

public class Adder {
    
    
    public int add(int a, int b) {
    
    
        return a + b;
    }

    public double add(double a, double b) {
    
    
        return a + b;
    }
}

In the above example, two methods Addernamed are defined in the class , one accepting two parameters of type and the other accepting two parameters of type. Through the different types of parameter lists, the method is overloaded , and the addition operation of integers and decimals is realized.addintdoubleadd

Seven, the method is simple to practice

1. Array traversal

Requirements: Design a method for traversing the array, requiring the results of the traversal to be on one line. For example: [11, 12, 13, 14, 15].

A method that iterates through the array and prints the result on one line can be devised in the following way:

public class ArrayTraversal {
    
    
    public static void main(String[] args) {
    
    
        int[] array = {
    
    11, 12, 13, 14, 15};
        traverseArray(array);
    }
    
    public static void traverseArray(int[] array) {
    
    
        System.out.print("[");
        for (int i = 0; i < array.length; i++) {
    
    
            System.out.print(array[i]);
            if (i != array.length - 1) {
    
    
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }
}

In the above example, a traverseArraymethod named is defined that accepts an intarray of type as a parameter. Inside the method, use forto loop through the array elements and print a comma and space after each element (unless it is the last element). Finally, the closing parenthesis is printed to complete the traversal result of the entire array.

Run the above code, the output is: [11, 12, 13, 14, 15].

2, the maximum value of the array

Requirement: Design a method to find the maximum value of the array and return the maximum value.

You can design a method to take the largest value in an array and return it using:

public class ArrayMaxValue {
    
    
    public static void main(String[] args) {
    
    
        int[] array = {
    
    11, 12, 13, 14, 15};
        int maxValue = findMaxValue(array);
        System.out.println("The maximum value in the array is: " + maxValue);
    }
    
    public static int findMaxValue(int[] array) {
    
    
        int maxValue = array[0];
        for (int i = 1; i < array.length; i++) {
    
    
            if (array[i] > maxValue) {
    
    
                maxValue = array[i];
            }
        }
        return maxValue;
    }
}

In the above example, we defined a findMaxValuemethod called that takes an intarray of type as a parameter and returns the largest value in the array.

Inside the method, we initialize a variable maxValueand set it as the first element of the array. We then use fora to loop through the remaining elements of the array and check whether each element is greater than maxValue. If so, the updated maxValuevalue is the value of the current element. Finally, we return maxValuethe value of .

Run the above code, the output is: The maximum value in the array is: 15.

3. Determine whether there is

Requirement: Define a method to judge whether a certain number in an array exists, and return the result to the caller.

You can use the following method to design a method to determine whether a certain number exists in an array and return the result to the caller:

public class ArrayContainsNumber {
    
    
    public static void main(String[] args) {
    
    
        int[] array = {
    
    11, 12, 13, 14, 15};
        int number = 14;
        boolean containsNumber = checkNumber(array, number);
        System.out.println("The array contains the number " + number + ": " + containsNumber);
    }
    
    public static boolean checkNumber(int[] array, int number) {
    
    
        for (int i = 0; i < array.length; i++) {
    
    
            if (array[i] == number) {
    
    
                return true;
            }
        }
        return false;
    }
}

In the above example, we defined a checkNumbermethod named , which accepts an intarray of type and a number to be judged as parameters, and returns a booleanvalue of type.

Inside the method, we use to forloop through each element of the array and check if the current element is equal to the number to be judged. If equal, return trueindicates that the number exists in the array. If no equal number is found after traversing the array, it returns to falseindicate that the number does not exist in the array.

Run the above code, the output is: The array contains the number 14: true.

4. Copy the array

Requirement: Define a method copyOfRange(int[] arr, int from, int to)
Function: start from the index from (including from) in the array arr.
Copy the elements up to the end of index to (not including to) into the new array, and return the array.

You can use the following methods to copy a specified range of elements in an array to a new array:

public class ArrayCopyOfRange {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    1, 2, 3, 4, 5, 6};
        int from = 2;
        int to = 5;
        int[] newArr = copyOfRange(arr, from, to);
        
        System.out.print("Original Array: ");
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i] + " ");
        }
        
        System.out.println();
        
        System.out.print("New Array: ");
        for (int i = 0; i < newArr.length; i++) {
    
    
            System.out.print(newArr[i] + " ");
        }
    }
    
    public static int[] copyOfRange(int[] arr, int from, int to) {
    
    
        int[] newArr = new int[to - from];
        int index = 0;
        
        for (int i = from; i < to; i++) {
    
    
            newArr[index] = arr[i];
            index++;
        }
        
        return newArr;
    }
}

In the above example, we defined a copyOfRangemethod called that takes an intarray of type , a start index fromand an end index toas parameters, and returns a new intarray of type .

Inside the method, we first create a new array newArrwith length to - from, the number of elements to copy. Then, use a loop fromto iterate from index to index in the original array to - 1and copy each element into the new array.

Finally, return the new array to the caller. In the method, we test the method mainwith an example array and the start index 2and end index . Running the above code will output:5copyOfRange

Original Array: 1 2 3 4 5 6
New Array: 3 4 5

Eight, the basic memory principle of the method

In Java, the execution and storage of methods in memory mainly involves two concepts: stack memory and heap memory.

  1. Stack Memory:

    • When a method is called, a new stack frame (Stack Frame) is created in the stack memory, and the stack frame stores information such as local variables, parameters, and method return values ​​of the method.
    • The stack memory has the characteristics of last-in-first-out. Every time a method is called, the stack frame will be pushed onto the top of the stack. After the method is executed, the stack frame will be popped.
    • The size of the stack memory is limited. When the call level of the method is too deep or the local variables in the method take up too much space, it may cause a stack overflow error (Stack Overflow Error).
  2. Heap Memory:

    • Dynamically allocated memory spaces such as objects and arrays are stored in heap memory.
    • The size of the heap memory is generally relatively large, and it is not easy to be exhausted.
    • The allocation and release of heap memory is handled by the garbage collection mechanism of the Java Virtual Machine (JVM).

The execution process of the method is as follows:

  1. When a method is called, a new stack frame is created in stack memory and pushed onto the top of the stack.
  2. The stack frame will contain the storage space for the method's local variables, parameters, and method return value.
  3. When the method is executed, memory space is allocated in the stack frame to store local variables.
  4. After the method is executed, the stack frame will be popped and the corresponding memory space will be released.
  5. The return value of the method is stored in the stack frame and passed to the calling method.

It should be noted that the parameter passing of the method is passed by value, that is, the copy of the variable is passed instead of the variable itself. For parameters of reference type, a copy of the reference is passed, not the object itself that the reference points to. Therefore, modifications to the parameters in the method will not affect the value of the original variable or object.

Nine, what are basic data types and reference data types

In Java, data types are divided into basic data types (Primitive Data Types) and reference data types (Reference Data Types).

  1. Basic data types:
    Basic data types are the most basic data types in the Java language. They are predefined and directly supported by the Java virtual machine. Basic data types include:

    • Integer (int, short, long, byte)
    • Floating point type (float, double)
    • character type (char)
    • boolean

    Features of basic data types:

    • The occupied memory space is fixed and will not change with the size of the data.
    • When assigning a value, what is directly stored is the value of the data itself, not a reference.
    • stored in stack memory.
  2. Reference Data Type:
    A reference data type refers to a type created through a class, interface, or array. A variable of reference data type stores a reference (memory address) to an object, not the object itself.

    • Type (Class)
    • Interface
    • Array (Array)

    Characteristics of reference data types:

    • The size of the memory space occupied is not fixed and is determined by the size of the object.
    • When assigning a value, the reference of the object is stored, and the properties and methods of the object can be accessed through the reference.
    • stored in heap memory.
    • Objects need to be created with the keyword "new".

It should be noted that primitive data types and reference data types are different when passing parameters. Parameter passing of primitive data types is passed by value, while parameter passing of reference data types is passed by reference. That is, the parameter passing of the basic data type is a copy of the passed value, and the parameter passing of the reference data type is the copy of the reference data type.

Ten, method value transfer

In Java, method parameter passing is passed by value (Pass by Value).

Passing by value means that when the method is called, the value of the actual parameter will be copied to the formal parameter, and the modification of the formal parameter in the method will not affect the value of the actual parameter.

Specifically, the value transfer of methods in Java has the following characteristics:

  1. Passing by value of a primitive data type: When a primitive data type is passed as a parameter to a method, what is passed is a copy of the value of that data. Modifications to the formal parameters inside the method will not affect the actual parameter values.
  2. Passing by value of a reference data type: When an object is passed as a parameter to a method, what is passed is a copy of the reference to the object. The modification of the formal parameter inside the method will affect the object pointed to by the actual parameter, but if the formal parameter is re-pointed to a new object inside the method, the reference of the actual parameter will not be affected.

The following example code is used to illustrate the value passing of the method:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int a = 10;
        changeValue(a);
        System.out.println(a); // 输出:10
        
        StringBuilder sb = new StringBuilder("Hello");
        changeReference(sb);
        System.out.println(sb.toString()); // 输出:Hello World
        
        changeValueReference(sb);
        System.out.println(sb.toString()); // 输出:Hello Java
    }
    
    public static void changeValue(int num) {
    
    
        num = 20;
    }
    
    public static void changeReference(StringBuilder str) {
    
    
        str.append(" World");
    }
    
    public static void changeValueReference(StringBuilder str) {
    
    
        str = new StringBuilder("Hello Java");
    }
}

In the above example, the changeValue method attempts to modify the value of the basic data type, but has no effect on the actual parameter a passed in.
The changeReference method modifies the incoming StringBuilder object through the reference type parameter, which affects the value of the actual parameter sb.
The changeValueReference method attempts to point the formal parameter str to a new StringBuilder object, but has no effect on the actual parameter sb.

Eleven, comprehensive exercises

1. Buy a plane ticket

Demand: The price of the air ticket is based on off-season and peak season, first class and economy class, enter the original price of the ticket, month and first class or economy class.
Air ticket prices are calculated according to the following rules: 10% off for first-class cabins during peak season (May-October). 15% discount for economy class, 30% discount for first class in off-season (November to April next year), 35% discount for economy class.

Here is a sample code that calculates the ticket price according to the rules based on the original ticket price, month and first class or economy class entered:

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("请输入机票原价:");
        double originalPrice = scanner.nextDouble();
        
        System.out.print("请输入月份(1-12):");
        int month = scanner.nextInt();
        
        System.out.print("请输入舱位(1-头等舱,2-经济舱):");
        int cabinType = scanner.nextInt();
        
        double discount = getCabinDiscount(month, cabinType);
        double finalPrice = originalPrice * discount;
        
        System.out.println("机票折扣后的价格为:" + finalPrice);
    }
    
    public static double getCabinDiscount(int month, int cabinType) {
    
    
        if (month >= 5 && month <= 10) {
    
     // 旺季
            if (cabinType == 1) {
    
     // 头等舱
                return 0.9;
            } else if (cabinType == 2) {
    
     // 经济舱
                return 0.85;
            }
        } else if (month >= 11 || month <= 4) {
    
     // 淡季
            if (cabinType == 1) {
    
     // 头等舱
                return 0.7;
            } else if (cabinType == 2) {
    
     // 经济舱
                return 0.65;
            }
        }
        
        return 1.0; // 默认折扣为1,即原价
    }
}

In the above code, we use the Scanner class to get the user's input, including the original price of the ticket, the month and the class of travel.
Then, calculate the discount for the ticket by calling the getCabinDiscount method, which returns the corresponding discount rate based on the input month and cabin type.
Finally, multiply the original price of the air ticket by the discount rate to get the final price of the air ticket, and output it to the user.

For example, if the user enters the original price of the air ticket as 1000, the month as 8, and the cabin type as 1 (first class), then the output price of the air ticket after discount is 900.

2. Find prime numbers

Requirement: Determine how many prime numbers there are between 101-200, and output index prime numbers.

The following is a sample code for judging how many prime numbers there are between 101-200, and outputting the index of prime numbers:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int count = 0;
        for (int i = 101; i <= 200; i++) {
    
    
            if (isPrime(i)) {
    
    
                count++;
                System.out.println("第 " + count + " 个素数是:" + i);
            }
        }
        System.out.println("101-200之间共有 " + count + " 个素数");
    }
    
    public static boolean isPrime(int n) {
    
    
        if (n <= 1) {
    
    
            return false;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
    
    
            if (n % i == 0) {
    
    
                return false;
            }
        }
        return true;
    }
}

In the above code, we use a loop to traverse the numbers between 101-200. For each number, call the isPrime method to determine whether it is prime. If it is a prime number, output the prime number's index (that is, the number of prime numbers) and value.

The isPrime method implements the logic for judging whether a number is prime. It first judges that if the number is less than or equal to 1, it is not a prime number and returns false directly. Then, use a loop to check for divisibility, starting at 2 and going up to the square root of the number. If a divisible number is found, it is not prime and returns false. If no divisible number is found after the loop ends, it is a prime number and returns true.

Executing the above code will output how many prime numbers there are between 101-200, and output the index and value of each prime number.

3. Develop verification code

Requirements: Define a method to randomly generate a 5-digit verification code.
Verification code format: the length is 5, the first four characters are uppercase letters or lowercase letters, and the last character is a number.

The following is a sample code for randomly generating a 5-digit verification code:

import java.util.Random;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        String code = generateCode();
        System.out.println("生成的验证码是:" + code);
    }
    
    public static String generateCode() {
    
    
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        // 生成前4位字母
        for (int i = 0; i < 4; i++) {
    
    
            // 随机生成字母的ASCII码
            int ascii = random.nextInt(26);
            // 判断是大写字母还是小写字母
            char letter = (random.nextBoolean() ? 'A' : 'a');
            // 拼接字母到验证码
            sb.append((char)(letter + ascii));
        }
        
        // 生成最后1位数字
        int number = random.nextInt(10);
        sb.append(number);
        
        return sb.toString();
    }
}

In the above code, we defined a generateCodemethod to generate the verification code. Use an StringBuilderobject to concatenate the resulting characters.

First, we use Randoma class to generate random numbers. In a loop we generate 4 random letters. Generate random ASCII codes (0-25) and decide whether to generate uppercase or lowercase letters based on random Boolean values. We then stitch the generated letters into the captcha.

Finally, we use to nextInt(10)generate a random number from 0-9 and splicing it to the last digit of the verification code.

Executing the above code will output a randomly generated 5-digit verification code.

4. Copying of array elements

Requirements: Copy the elements of an array to another new array.

The following is a sample code that implements copying of array elements:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[] arr1 = {
    
    1, 2, 3, 4, 5};
        int[] arr2 = copyArray(arr1);
        
        System.out.println("原始数组:");
        for (int num : arr1) {
    
    
            System.out.print(num + " ");
        }
        
        System.out.println("\n复制后的数组:");
        for (int num : arr2) {
    
    
            System.out.print(num + " ");
        }
    }
    
    public static int[] copyArray(int[] arr) {
    
    
        int[] newArr = new int[arr.length];
        
        // 遍历原始数组,将每个元素复制到新数组中
        for (int i = 0; i < arr.length; i++) {
    
    
            newArr[i] = arr[i];
        }
        
        return newArr;
    }
}

In the above code, we define a copyArraymethod to copy the elements of the array. We pass in an original array and create a new array newArrwith the same length as the original array.

We then use a loop to iterate through the original array, copying each element to its corresponding position in the new array.

Finally, we return the new array.

Executing the above code will output the original array and the copied array.

5. Judges score

Requirement: In the singing competition, there are 6 judges to score the contestants, and the range of scores is an integer between [0-100]. The final score of the contestant is: the average score of the 4 judges after removing the highest and lowest scores. Please complete the above process and calculate the contestant's score.

The following is a sample code that implements scoring by judges:

import java.util.Arrays;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[] scores = {
    
    90, 95, 88, 92, 96, 85};
        double averageScore = calculateAverageScore(scores);
        
        System.out.println("评委打分:" + Arrays.toString(scores));
        System.out.println("选手得分:" + averageScore);
    }
    
    public static double calculateAverageScore(int[] scores) {
    
    
        // 对打分数组进行排序
        Arrays.sort(scores);
        
        // 去掉最高分和最低分的总分
        int totalScore = 0;
        for (int i = 1; i < scores.length - 1; i++) {
    
    
            totalScore += scores[i];
        }
        
        // 计算平均分
        double averageScore = (double) totalScore / (scores.length - 2);
        return averageScore;
    }
}

In the above code, we defined a calculateAverageScoremethod to calculate the player's score. We pass in an array of judges' scores.

First, we use Arrays.sortthe method to sort the array of scores so that the highest and lowest scores are at the beginning and end of the array, respectively.

Then, we use a loop to traverse the sorted scoring array, accumulating the total score from the second element to the penultimate element.

Finally, we calculate the average of the total scores minus the highest and lowest scores and return this as the player's score.

Executing the above code will output the judges' scores and the contestants' scores.

6. Digital encryption and decryption

encryption

Requirement: The digital password (greater than 0) of a certain system, such as 1983, is transmitted in an encrypted manner.
Rules: Get each number first, then add 5 to each number, then calculate the remainder of 10, and finally reverse all the numbers to get a series of new numbers.

The following is a sample code that implements digital encryption:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int password = 1983;
        int encryptedPassword = encryptPassword(password);
        
        System.out.println("原始密码:" + password);
        System.out.println("加密后的密码:" + encryptedPassword);
    }
    
    public static int encryptPassword(int password) {
    
    
        // 将密码转换为字符串
        String passwordStr = String.valueOf(password);
        
        // 将每位数加上5并对10求余
        StringBuilder encryptedPasswordStr = new StringBuilder();
        for (int i = 0; i < passwordStr.length(); i++) {
    
    
            int digit = Character.getNumericValue(passwordStr.charAt(i));
            int encryptedDigit = (digit + 5) % 10;
            encryptedPasswordStr.append(encryptedDigit);
        }
        
        // 反转字符串得到加密后的密码
        String reversedPasswordStr = encryptedPasswordStr.reverse().toString();
        int encryptedPassword = Integer.parseInt(reversedPasswordStr);
        
        return encryptedPassword;
    }
}

In the above code, we defined a encryptPasswordmethod to encrypt the password. We pass in a numeric password greater than 0.

First, we convert the password to a string so we can handle each digit easily.

Then, we use a loop to traverse each digit of the password, add 5 to each digit and take the remainder of 10 to get the encrypted digit. We use StringBuilderto build the encrypted password string.

Next, we reverse the encrypted password string to get the encrypted password string.

Finally, we convert the encrypted password string to integer form and return it as the encrypted password.

Executing the above code will output the original password and encrypted password.

decrypt

The following is a sample code that implements digital decryption:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int encryptedPassword = 8321;
        int decryptedPassword = decryptPassword(encryptedPassword);
        
        System.out.println("加密后的密码:" + encryptedPassword);
        System.out.println("解密后的密码:" + decryptedPassword);
    }
    
    public static int decryptPassword(int encryptedPassword) {
    
    
        // 将加密后的密码转换为字符串
        String encryptedPasswordStr = String.valueOf(encryptedPassword);
        
        // 反转字符串得到加密前的密码
        StringBuilder decryptedPasswordStr = new StringBuilder(encryptedPasswordStr).reverse();
        
        // 将每位数减去5并对10求余
        StringBuilder passwordStr = new StringBuilder();
        for (int i = 0; i < decryptedPasswordStr.length(); i++) {
    
    
            int digit = Character.getNumericValue(decryptedPasswordStr.charAt(i));
            int passwordDigit = (digit + 5) % 10;
            passwordStr.append(passwordDigit);
        }
        
        // 将加密前的密码字符串转换为整数形式,并将其作为解密后的密码返回
        int decryptedPassword = Integer.parseInt(passwordStr.toString());
        
        return decryptedPassword;
    }
}

In the above code, we define a decryptPasswordmethod to decrypt the encrypted password. We pass in an encrypted password.

First, we convert the encrypted password to a string.

Then, we reverse the encrypted password string to get the unencrypted password string.

Next, we use a loop to traverse the digits of the password string before encryption, subtract 5 from each digit and take the remainder of 10 to get the decrypted digits. We use StringBuilderto build the decrypted password string.

Finally, we convert the decrypted password string to integer form and return it as the decrypted password.

Executing the above code will output the encrypted password and decrypted password.

7. Grab red packets

Requirement: An anchor broadcasts a lottery draw, and the prize is a cash red envelope, with five bonuses of {2, 588, 888, 1000, 10000} respectively. Please use the code to simulate a draw, print out each award, and the order of appearance of the awards should be random and not repeated. The printing effect is as follows: (Random order, not necessarily the following order) A
bonus of 2 yuan is drawn
A bonus of 588 yuan is drawn
A bonus of 888 yuan is drawn
A bonus of 1,000 yuan is drawn
A bonus of 10,000 yuan is drawn

The following is the sample code for grabbing red envelopes:

import java.util.Random;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[] prizes = {
    
    2, 588, 888, 1000, 10000};
        
        shufflePrizes(prizes);
        
        for (int prize : prizes) {
    
    
            System.out.println(prize + "元的奖金被抽出");
        }
    }
    
    public static void shufflePrizes(int[] prizes) {
    
    
        Random random = new Random();
        
        for (int i = prizes.length - 1; i > 0; i--) {
    
    
            int j = random.nextInt(i + 1);
            
            int temp = prizes[i];
            prizes[i] = prizes[j];
            prizes[j] = temp;
        }
    }
}

In the above code, we use an array prizesto store the bonus amount. Then we call shufflePrizesthe method to shuffle the bonus order.

In shufflePrizesthe method, we use the Fisher-Yates algorithm to randomly shuffle the bonus array. By iterating the array, we use the method in each iteration nextIntto generate a random index j(range 0 to i), then swap the current iteration index iand jthe bonus amount at the random index.

Finally, in the method we mainiterate through the shuffled prize array and print each prize.

Executing the above code will output each award, and the order of appearance of the awards is random and not repeated.

8. Shuangseqiu lottery system

Requirements: The betting number consists of 6 red ball numbers and 1 blue ball number. Red ball numbers are chosen from 1-33; blue numbers are chosen from 1-16.

Winning Conditions and Prize Table

award etc. Winning conditions Winning description bonus
first prize 6 red balls, 1 basketball Medium 6+1 10 million
second prize 6 red balls, 0 basketballs Medium 6+0 5000000
third prize 5 red balls, 1 basketball Medium 5+1 3000 yuan
Fourth Prize 5 red balls, 0 basketballs
4 red balls, 1 basketball
Medium 5+0
Medium 4+1
200 yuan
fifth prize 4 red balls, 1 basketball
3 red balls, 1 basketball
Medium 4+0
Medium 3+1
10 yuan
Sixth Prize 2 red balls, 1 basketball 1
red ball, 1 basketball
0 red balls, 1 basketball
Medium 2+1
Medium 1+1
Medium 0+1
5 yuan

The following is a simple Java code implementation of the double color ball lottery system:

import java.util.Arrays;
import java.util.Random;

public class DoubleColorBallLottery {
    
    
    private static final int RED_BALL_COUNT = 6;
    private static final int MAX_RED_BALL_NUMBER = 33;
    private static final int MAX_BLUE_BALL_NUMBER = 16;

    private static final int FIRST_PRIZE = 10000000; // 一等奖奖金
    private static final int SECOND_PRIZE = 5000000; // 二等奖奖金
    private static final int THIRD_PRIZE = 3000; // 三等奖奖金
    private static final int FOURTH_PRIZE = 200; // 四等奖奖金
    private static final int FIFTH_PRIZE = 10; // 五等奖奖金
    private static final int SIXTH_PRIZE = 5; // 六等奖奖金

    private static final int[] FIRST_PRIZE_CONDITION = {
    
    6, 1}; // 一等奖中奖条件
    private static final int[] SECOND_PRIZE_CONDITION = {
    
    6, 0}; // 二等奖中奖条件
    private static final int[] THIRD_PRIZE_CONDITION = {
    
    5, 1}; // 三等奖中奖条件
    private static final int[] FOURTH_PRIZE_CONDITION = {
    
    5, 0, 4, 1}; // 四等奖中奖条件
    private static final int[] FIFTH_PRIZE_CONDITION = {
    
    4, 1, 3, 1}; // 五等奖中奖条件
    private static final int[] SIXTH_PRIZE_CONDITION = {
    
    2, 1, 1, 1, 0, 1}; // 六等奖中奖条件

    public static void main(String[] args) {
    
    
        int[] winningNumbers = generateWinningNumbers();
        int[] userNumbers = generateUserNumbers();
        int blueBall = generateBlueBall();

        System.out.println("中奖号码:" + Arrays.toString(winningNumbers) + " 蓝球:" + blueBall);
        System.out.println("用户号码:" + Arrays.toString(userNumbers) + " 蓝球:" + blueBall);

        int prizeLevel = checkPrizeLevel(winningNumbers, userNumbers, blueBall);
        switch (prizeLevel) {
    
    
            case 1:
                System.out.println("恭喜您中一等奖!奖金:" + FIRST_PRIZE + "元");
                break;
            case 2:
                System.out.println("恭喜您中二等奖!奖金:" + SECOND_PRIZE + "元");
                break;
            case 3:
                System.out.println("恭喜您中三等奖!奖金:" + THIRD_PRIZE + "元");
                break;
            case 4:
                System.out.println("恭喜您中四等奖!奖金:" + FOURTH_PRIZE + "元");
                break;
            case 5:
                System.out.println("恭喜您中五等奖!奖金:" + FIFTH_PRIZE + "元");
                break;
            case 6:
                System.out.println("恭喜您中六等奖!奖金:" + SIXTH_PRIZE + "元");
                break;
            default:
                System.out.println("很遗憾,未中奖");
                break;
        }
    }

    // 生成中奖号码
    private static int[] generateWinningNumbers() {
    
    
        int[] winningNumbers = new int[RED_BALL_COUNT];
        Random random = new Random();
        for (int i = 0; i < RED_BALL_COUNT; i++) {
    
    
            int number = random.nextInt(MAX_RED_BALL_NUMBER) + 1;
            while (containsNumber(winningNumbers, number)) {
    
    
                number = random.nextInt(MAX_RED_BALL_NUMBER) + 1;
            }
            winningNumbers[i] = number;
        }
        Arrays.sort(winningNumbers);
        return winningNumbers;
    }

    // 生成用户号码
    private static int[] generateUserNumbers() {
    
    
        int[] userNumbers = new int[RED_BALL_COUNT];
        Random random = new Random();
        for (int i = 0; i < RED_BALL_COUNT; i++) {
    
    
            int number = random.nextInt(MAX_RED_BALL_NUMBER) + 1;
            while (containsNumber(userNumbers, number)) {
    
    
                number = random.nextInt(MAX_RED_BALL_NUMBER) + 1;
            }
            userNumbers[i] = number;
        }
        Arrays.sort(userNumbers);
        return userNumbers;
    }

    // 生成蓝球号码
    private static int generateBlueBall() {
    
    
        Random random = new Random();
        return random.nextInt(MAX_BLUE_BALL_NUMBER) + 1;
    }

    // 检查中奖等级
    private static int checkPrizeLevel(int[] winningNumbers, int[] userNumbers, int blueBall) {
    
    
        int redBallCount = countRedBalls(winningNumbers, userNumbers);
        boolean hasBlueBall = blueBall == userNumbers[RED_BALL_COUNT - 1];

        if (Arrays.equals(userNumbers, winningNumbers)) {
    
    
            return 1;
        } else if (redBallCount == FIRST_PRIZE_CONDITION[0] && hasBlueBall) {
    
    
            return 2;
        } else if (redBallCount == THIRD_PRIZE_CONDITION[0] && hasBlueBall) {
    
    
            return 3;
        } else if (redBallCount == FOURTH_PRIZE_CONDITION[0] && hasBlueBall) {
    
    
            return 4;
        } else if (redBallCount == FOURTH_PRIZE_CONDITION[2] && hasBlueBall) {
    
    
            return 4;
        } else if (redBallCount == FIFTH_PRIZE_CONDITION[0] && hasBlueBall) {
    
    
            return 5;
        } else if (redBallCount == FIFTH_PRIZE_CONDITION[2] && hasBlueBall) {
    
    
            return 5;
        } else if (redBallCount == SIXTH_PRIZE_CONDITION[0] && hasBlueBall) {
    
    
            return 6;
        } else if (redBallCount == SIXTH_PRIZE_CONDITION[2] && hasBlueBall) {
    
    
            return 6;
        } else if (redBallCount == SIXTH_PRIZE_CONDITION[4] && hasBlueBall) {
    
    
            return 6;
        } else if (!hasBlueBall) {
    
    
            return 0;
        } else {
    
    
            return -1;
        }
    }

    // 统计红球个数
    private static int countRedBalls(int[] winningNumbers, int[] userNumbers) {
    
    
        int count = 0;
        for (int userNumber : userNumbers) {
    
    
            if (containsNumber(winningNumbers, userNumber)) {
    
    
                count++;
            }
        }
        return count;
    }

    // 检查数组中是否包含指定的数字
    private static boolean containsNumber(int[] numbers, int number) {
    
    
        for (int i : numbers) {
    
    
            if (i == number) {
    
    
                return true;
            }
        }
        return false;
    }
}

In the above code, we use generateWinningNumbersmethod and generateUserNumbersmethod to generate winning numbers and user numbers respectively, and the generated numbers are all 6 red ball numbers and 1 blue ball number.

Then use generateBlueBallthe method to generate a blue ball number.

Next, we use checkPrizeLevelthe method to check if the user number is a winner and return the winning rank. The method judges the winning level according to the winning conditions in the bonus table.

Finally, according to the returned winning level, we print the winning information and bonus amount.

Executing the above code will output the winning number, user number and winning information.

9. Two-dimensional array

A two-dimensional array in Java is a data structure composed of multiple one-dimensional arrays, which can be regarded as a table or a matrix. A two-dimensional array is defined in Java as an array of arrays, that is, the elements of the array are also arrays.

(1) Static initialization of two-dimensional array

In Java, two-dimensional arrays can be created and initialized using static initialization. Static initialization refers to assigning values ​​to the array elements at the same time as declaring the array. The following is an example of statically initializing a two-dimensional array:

dataType[][] arrayName = {
    
    
    {
    
    value1, value2, value3},
    {
    
    value4, value5, value6},
    {
    
    value7, value8, value9}
};

In the above example, dataType represents the data type of elements in the two-dimensional array, arrayName is the name of the array, {value1, value2, value3} represents the elements of the first row, and {value4, value5, value6} represents the elements of the second row , {value7, value8, value9} represent the elements of the third row.

Rows and columns can be added or removed as needed to make a two-dimensional array of different sizes. The number of elements in each row can vary, creating an irregular two-dimensional array.

Here is a complete example of statically initializing a two-dimensional array:

int[][] matrix = {
    
    
    {
    
    1, 2, 3},
    {
    
    4, 5, 6},
    {
    
    7, 8, 9}
};

// 访问二维数组的元素
int element = matrix[1][2]; // 访问第二行第三列的元素,即6

// 遍历二维数组的所有元素
for (int i = 0; i < matrix.length; i++) {
    
    
    for (int j = 0; j < matrix[i].length; j++) {
    
    
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

In the above example, a 3x3 two-dimensional array is created, and then elements in it are accessed through indexes, and nested loops are used to traverse all elements in the two-dimensional array. The output is:

1 2 3 
4 5 6 
7 8 9

(2) Dynamic initialization of two-dimensional array

In Java, two-dimensional arrays can be created and initialized using dynamic initialization. Dynamic initialization refers to specifying the size of the array while declaring the array, and then using loops or other methods to assign values ​​to the array elements. Here is an example of dynamically initializing a two-dimensional array:

dataType[][] arrayName = new dataType[rowSize][columnSize];

In the above example, dataType indicates the data type of elements in the two-dimensional array, arrayName is the name of the array, rowSize indicates the number of rows in the array, and columnSize indicates the number of columns in the array.

Here is a complete example of dynamically initializing a two-dimensional array:

int rowSize = 3;
int columnSize = 3;
int[][] matrix = new int[rowSize][columnSize];

// 为二维数组赋值
for (int i = 0; i < rowSize; i++) {
    
    
    for (int j = 0; j < columnSize; j++) {
    
    
        matrix[i][j] = i + j;
    }
}

// 访问二维数组的元素
int element = matrix[1][2]; // 访问第二行第三列的元素,即3

// 遍历二维数组的所有元素
for (int i = 0; i < rowSize; i++) {
    
    
    for (int j = 0; j < columnSize; j++) {
    
    
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

In the above example, newa 3x3 two-dimensional array is dynamically created through keywords, and then nested loops are used to assign values ​​to the array elements. Next, access the elements by index, and use nested loops to iterate through all the elements in the two-dimensional array. The output is:

0 1 2 
1 2 3 
2 3 4

(3) Two-dimensional array memory map

Here is an example memory map of a Java two-dimensional array:

+---------+
|   row0  | -> +-------+
|         |    |   1   |
+---------+    +-------+
|   row1  | -> +-------+
|         |    |   2   |
+---------+    +-------+
|   row2  | -> +-------+
|         |    |   3   |
+---------+    +-------+

In memory, a two-dimensional array is stored as a set of contiguous blocks of memory. Each memory block represents a row of the array, and the size of the memory block depends on the type of the array element. In the above example, the 2D array has 3 rows and 1 column, so there are 3 contiguous blocks of memory in memory.

Each memory block stores the value of the array element. In the example above, the first row has an element value of 1, the second row has an element value of 2, and the third row has an element value of 3.

To access a specific element in a two-dimensional array, you can use indexing. For example, to access the value of the first element of the second row, you can use arrayName[1][0]. In the above example, arrayName[1][0]the value of 2.

It is important to note that a two-dimensional array in Java is an array of one-dimensional arrays. That is, a two-dimensional array is actually an array containing other one-dimensional arrays. Each 1D array represents a row of a 2D array. In memory, each element of a two-dimensional array is actually a reference to a one-dimensional array.

(4) Calculate sales for each quarter

The following is a Java example that uses a two-dimensional array to calculate sales for each quarter:

public class Sales {
    
    
    public static void main(String[] args) {
    
    
        // 定义二维数组sales,表示每个季度的销售额
        double[][] sales = {
    
    
            {
    
    1500.0, 2000.0, 1800.0},   // 第一季度的销售额
            {
    
    2200.0, 2500.0, 2300.0},   // 第二季度的销售额
            {
    
    1800.0, 2100.0, 1900.0},   // 第三季度的销售额
            {
    
    2500.0, 2800.0, 2600.0}    // 第四季度的销售额
        };

        // 计算每个季度的总销售额
        double[] totalSales = new double[4];
        for (int i = 0; i < sales.length; i++) {
    
    
            double total = 0.0;
            for (int j = 0; j < sales[i].length; j++) {
    
    
                total += sales[i][j];
            }
            totalSales[i] = total;
        }

        // 输出每个季度的总销售额
        for (int i = 0; i < totalSales.length; i++) {
    
    
            System.out.println("第" + (i+1) + "季度的总销售额为:" + totalSales[i]);
        }
    }
}

In the above example, we use a two-dimensional array salesto represent the sales for each quarter. Each row of the array represents a quarter, and each column represents a month. We first define this two-dimensional array and initialize the sales for each quarter.

Next, we create a 1D array totalSalesto store the total sales for each quarter. Then, the two-dimensional array is traversed through nested loops, the total sales for each quarter are calculated, and the results are stored in totalSalesthe array.

Finally, we loop through totalSalesthe array and output the total sales for each quarter.

Running the above code will output the total sales for each quarter.

Guess you like

Origin blog.csdn.net/m0_62617719/article/details/132558890