Function method details

Posted by hakmir on Wed, 15 Dec 2021 00:37:25 +0100

Use the loop to let the user enter an integer. If the entered integer is 0, the loop will jump out.
The demo code is as follows:

package com.txw.test;

import java.util.Scanner;
public class Test {
    public static void main(String[]args) {
        Scanner sc = new Scanner(System.in);
        while (true){
            int n = sc.nextInt();
            if (n % 2 ==0){
                break;
            }
        }
    }
}

1. Function

  • Concept: a group of codes that realize specific functions. The codes are defined into functions and can be used repeatedly to reduce code redundancy and improve program reusability and Maintainability (scalability).
  • Define the position of the function: within the class and outside other functions.
    demonstration:
    class Test{
        // 1
        public static void main(String[]args){
            
        }
        // 2
    }
    
  • Define the syntax of the function:
Access modifier static Return value type function name( Parameter table ){
 	// [function body] stores the function code, which is executed when the function is called   
}

The demo code is as follows:

package com.txw.test;

public class Test {
    public static void main(String[]args) {
        fn();
    }
    public static  void fn (){
        System.out.println("Hello,World!");
    }
}

When you run a program using the java command, the JVM only calls the main function to execute the code in the main function.

2. Components of function
  • Function name: the identification of the function needs to meet the identifier syntax specification. When calling the function, the function name needs to be used for calling.
  • Function body: the function code used to store the function, called the implementation of the function (function), is executed when the function is called.
  • Parameter table and parameters, as shown in the figure:

    Parameters: the demands of the function specify the data required by the function, which needs to be defined in the parameter table. It is a special local variable in the function. Any known data type can be used for parameters, and the number of parameters is unlimited.
    Parameter table: define the position of parameters and define parameters in the parameter table.
    Syntax for defining parameters:
Access modifier static Return value type function name(Data type parameter name 1 , Data type parameter name 2, Data type parameter name 3....){
 	//[function body] stores the function code, which is executed when the function is called   
}
//The data type parameter name constitutes a parameter, and a parameter represents a request

Note: not all functions require parameters. Parameters can only be set when the function requires the caller to provide data. As shown in the figure:

The demo code is as follows:

package com.txw.test;

public class Test {
    public static void main(String[]args) {
        // Function user 
        print(10,"Copy of ID card");     // Print 10 copies of ID card 
        print(15,"Copy of household register");     // Print 15 copies of household register
    }
    // When the program is executed, the actual parameter assigns a value to the formal parameter, and the function uses the formal parameter to complete the function
    // Function provider (print shop)
    // Demand: print content (String), print quantity (int)
    public static void print(int c,String str){
        // 1000
        for(int i=1; i<=c; i++){    // Print separator
            System.out.print( str );
        }
        System.out.println();   // Line feed
    }
}
  • Formal parameter: the parameter defined in the function parameter table. It is only used to describe a form of function demand.
    Instance parameter: the parameter with actual data passed in when calling the function.

  • Return value type and return value.
    Return value type: constrains what type of data the function returns. Any known type can be used. void means that no result will be returned.
    Return value: the data to be returned by the function.

    Return (return statement)
    If the return value type of the function is not void, you must use the return statement to return a result, otherwise there is a compilation error.
    Syntax:

    return Return value;
    

    Example: define a function that accepts two integers a and B, calculates the sum of the two integers and returns the result. As shown in the figure:
    The demo code is as follows:

package com.txw.test;

import java.util.Scanner;
public class Test{
	public static void main(String[]args){
		Scanner sc =  new Scanner(System.in);
		System.out.println("Please enter two integers:");
		int num1 = sc.nextInt();
		int num2 = sc.nextInt();
		int n = sum(num1,num2);
		// Print the results returned by sum
		System.out.println( n );
	}
	
	// Define a function to calculate the sum of two integers and print out the result
	// Two integers are required
	// Return value type: int means that sum will return data of type int
	public static int sum(int a, int b){
			// Return value
			int r = a + b;
			//Returns the variable r as a result
			return r;
	}
}

When the return statement is executed, the function will immediately return the location where the carried result is generated to the calling function.
Return value used by function Caller:

// 1. Directly use the return value to complete the function
System.out.println( sum(10,20) );
// 2. Use variable after receiving
int n = sum(10,20);
System.out.println( n );

Note when using return:

  1. The return statement will jump out of the function when it is executed, which can be used for the flow control statement of the function.
  2. Return can be used if the return value type is void; Process control.
  3. The return defined in the for or if statement may not be executed, and there may be an error of missing the return statement.
    Usually, the return statement will appear on the last line of code when it needs to return results.
Three elements of function
  • Three important components
    1. Function name: the identification of the function needs to meet the identifier syntax specification. When calling the function, the function name needs to be used for calling.
    2. Parameter table: define the position of parameters and define parameters in the parameter table.
    3. Return value type: constrains what type of data the function returns. Any known type can be used, void Indicates that no results will be returned.
    
  • The function name, parameter table and return value type constitute the declaration of the function.
4 call function
  • Syntax: function name (argument);
    For example:
    fn(); 		// fn is the function name
    
    Function execution process:
When calling a function `Argument`by`Formal parameter`Assignment, the function uses formal parameters to complete the calculation result
 After the result is obtained, the result can be`Returns to the location at the time of the call`Generate results

As shown in the figure:

Nested execution process of functions: call functions in functions. As shown in the figure:

5. Exercises

  1. For functions, the following description is correct (a, B, c).
    A. Function definition is divided into function declaration and implementation.
    B. Multiple functions can be defined in a class.
    C. If the called function has a return value, the caller must process the return value, otherwise the compilation will report an error.
    D. The argument of a function is to assign a value to a formal parameter.
    Cause: C option error: the return value of the function needs to be acceptable, not required.
  2. Which of the following functions are defined correctly (a, c).
    A. public static void m1{}
    B. public void static m2(){}
    C. public static int m3(int m){ return m; }
    D. Public static void m4(int a,b,c){}
    Reason: the B option is wrong because static should be placed before the return value type. The D option is wrong because the P of public should be lowercase.
  3. If a defined function has a return value, the following description of the function call is wrong (D).
    A. Function calls can exist as separate statements.
    B. A function call can be used as an argument to a function.
    C. Function calls can be applied to an expression.
    D. Function calls can be used as formal parameters of a function.
  4. Calling a function with a return value determines which part of the result type to get ©.
    A. The return value in the return statement.
    B. The data passed when the function is called.
    C. The return value type of the function declaration.
    D. System default assignment.
  5. Carefully read whether the following program code is correct. If it is correct, write the printout result; Otherwise, explain the cause of the error.
    The code is as follows:
package com.txw.test;

public class Test {
   public static void main(String[]args) {
       int m = 1, n =  3;
       m1(m ,n);
       System.out.println(m,n);
   }
   public static void m1(int a ,int b){
       int temp = a;
       a = b;
       b = temp;
   }
}

Answer: wrong. Error:(6, 30) java: null type is not allowed here.
6 programming: write a function add, accept two integers as parameters, and return the sum of the two integers; Invoke and print the result in the main function.
The demo code is as follows:

package com.txw.test;

public class Test {
    public static void main(String[]args) {
        // Function call and return the result
        System.out.println(add(5,2));
    }
    // Define a function to complete the addition and summation of two int type data
    private static int add(int a, int b) {
        // Returns the result to the call location
        return a + b;
    }
}
  1. Programming: write a function, accept an integer n, and output all the factors of this integer; And call this function in the main function.
    The demo code is as follows:
package com.txw.test;

public class Test {
    public static void main(String[]args) {
        allFact(1000);
    }
    // Define a function to receive an integer and output all the factors of the integer
    public static void allFact(int n){
        // The factor includes 1, not itself. All factors that can be divided are factors, so the maximum factor will not exceed half of the value
        for(int i = 1; i <= n / 2; i++){
            if (n % i == 0){
                System.out.print(i + "\t");
            }
        }
    }
}
  1. Programming: write a function, accept an integer n, and output the sum of 1 + 2 + 3 +... + n; Call this function in the main function.
    The demo code is as follows:
package com.txw.test;

public class Test {
    public static void main(String[]args) {
        // Call the function to print the result
        System.out.println(sum(100));
    }
    // Define a function to receive an integer n and return the sum of all numbers from 1 to n
    public static int sum(int n){
        // Define summation variables
        int sum = 0;
        // Cycle from 1 to n
        for (int i = 1; i <= n; i ++){
            // Each value is added to sum
            sum += i;
        }
        // The end of the loop returns the result to the call location
        return sum;
    }
}
  1. Programming: write a function, accept an integer parameter n, and output n HelloWorld; Call this function in the main function.
    The demo code is as follows:
package com.txw.test;

public class Test {
    public static void main(String[]args) {
       printHelloWorld(5);
    }
    // Define a function to receive integer n and print n "hello world"
   public static void printHelloWorld(int n){
       for (int i = 1; i <=n; i++) {
           System.out.println("hello world");
       }
   }
}
  1. Programming: write a function, accept an integer, and output how many digits this integer is.
    The demo code is as follows:
package com.txw.test;

public class Test {
    public static void main(String[]args) {
        System.out.println(wei(222));
    }
    // Define a function to receive an integer n and find out how many bits n has
    public static int wei(int n){
        // Count the number of bits of an integer
        int w = 0;
        do{
            // An integer has at least 1 bit, so + 1 first
            w++;
            // Every time you divide by 10, the result is not 0, indicating that the number of digits needs to be + 1
            n = n /10;
        }while(n!=0);
        return w;
    }
}
  1. Programming: find a three digit number, which is the sum of the factorials of each digit.
    The demo code is as follows:
package com.txw.test;

public class Test {
    public static void main(String[]args) {
        // Find a three digit number, which is the sum of the factorials of each digit
        // Loop to get all three digits
        for (int i = 100; i <= 999; i++) {
            // Get every three digit ten hundred
            int a = i / 100; int b = i / 10 % 10;
            int c = i % 10;
            // If the factorial sum of the tens and hundreds of digits is equal to the three digits\
            if (jieCheng(a) + jieCheng(b) + jieCheng(c) == i) {
                // Print this three digit number
                System.out.println(i);
            }
        }
    }
    // Factorial function
    public static int jieCheng(int n) {
        int sum = 1;
        for (int i = 2; i <= n; i++) {
            sum *= i;
        }
        return sum;
    }
}
  1. Programming: if the sum of all factors of integer A (including 1, excluding A itself) is equal to B, and the sum of all factors of integer B (including 1, excluding B itself) is equal to A, then integer A\B is A pair of intimate numbers; find all intimate numbers within 3000.
    The demo code is as follows:
package com.txw.test;

public class Test {
    public static void main(String[]args) {
        for (int i = 1; i <= 3000; i++) {
            int b = sumAllFact(i); // The sum of the factors of i is b
            int a = sumAllFact(b); // The sum of the factors of b is a
            // Analysis: if a == i, it means that the sum of factors of a is b,
            // The factor sum of b is a, which meets the requirement of intimacy number
            // At the same time, in order to avoid repeated solutions, a < B is required
            if (a < b && a == i) {
                System.out.println(a + " " + b);
            }
        }
    }
    // Function for calculating the sum of factors
    public static int sumAllFact(int n) {
        int sum = 0;
        for (int i = 1; i <= n / 2; i++) {
            if (n % i == 0){
                sum += i;
            }
        }return sum;
    }
}

Verify Goldbach's conjecture: any even number greater than 6 can be decomposed into the sum of two prime numbers. It is required to input an integer and output the sum of which two prime numbers this number can be decomposed into.
For example, enter an integer 14 and output the result: 14 = 3 + 11 14 = 7 + 7.
The demo code is as follows:

package com.txw.test;

import java.util.Scanner;
public class Test {
    public static void main(String[]args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 3; i <= n / 2; i += 2) {
            // Split n into I and n-i
            // Judge whether i and n-1 are prime numbers respectively
            // If both numbers are prime numbers, it is proved that this is a set of solutions
            if (isPrime(i) && isPrime(n - i)) {
                System.out.println(n + "=" + i + "+" + (n - i));
            }
        }
    }
    public static boolean isPrime(int n) {
        for (int i = 2; i <= Math.sqrt(n); i ++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
}

The summary is shown in the figure:

Topics: Java JavaSE