Summer Java study notes (2)

1. Java method: A Java method is a collection of statements that together perform a function.

  • A method is an ordered combination of steps to solve a class of problems
  • method contained in a class or object
  • Methods are created in the program and referenced elsewhere

(1) Method command rules: The first word of the method name should start with a lowercase letter, and the following words should start with an uppercase letter without using a hyphen. Such as addMethod, add_Method

(2) Method definition and call

        A method with a return value (such as int, string) must have a return statement, while a void method is an empty method, you can use System.out.println("return a statement"); output statement

        Use the parameter type parameter name in the method to realize the data transfer of the parameter, and pass in the data in the main method for processing

//修饰符 返回值类型 方法名(参数类型 参数名){
//    ...
//    方法体
//    ...
//    return 返回值;
//}

public class 方法 {
    public static void main(String[] args) {
        System.out.println(add(1,2));
        printGrade(78);
    }
    
    //传入两个数 进行加和
    public static int add(int a,int b){
        return a+b;
    }
    
    //获取成绩并判断等级  用输出语句输出
    public static void printGrade(double score) {
        if (score >= 90.0) {
            System.out.println('A');
        }
        else if (score >= 80.0) {
            System.out.println('B');
        }
        else if (score >= 70.0) {
            System.out.println('C');
        }
        else if (score >= 60.0) {
            System.out.println('D');
        }
        else {
            System.out.println('F');
        }
    }
}

(2) Variable scope: The scope of a variable is the part of the program where the variable can be referenced.

        Variables defined within a method are called local variables; the scope of a local variable starts from the declaration and ends at the end of the block containing it; local variables must be declared before they can be used

        Pay attention to the scope of variables in the method, the variables declared in the method can only be used in the method

Guess you like

Origin blog.csdn.net/laodaye_xiaolizi/article/details/130917445