Nine -1, methods of use

First, how to define the method

1, the method defined: means for solving a class of problems ordered combination code, is a functional block

2, define a method syntax:

2.1, access modifiers: currently only use the public in the early stages.

2.2 Return Value: If the method does not return any value, designated as the return value of type void; If the method has a return value, it is necessary to specify the type of the return value, and using a return statement in the body of the return value of the method

2.3, method name: the name of the method definition, must use a valid identifier, the general method of the first letter lowercase, uppercase first letter of the second word, and so on.

2.4, parameter list: the list of parameters passed to the method, there may be multiple parameters, separated by commas between the plurality of parameters, each parameter by the parameter type and a parameter name, separated by spaces.

3, according to whether the reference method with, or without the return value, the method can be divided into four categories:  

  • None None Return Value Method Reference
  • No reference method return value
  • None Return Value Method parameterized
  • Method return value parameterized

4, using the two-step method

4.1, the definition of methods:

For example: the FIG code defines a method called the helloWorld, no parameters, and the method returns no value, the output operation is performed: welcome to hello world!

 

 It should be noted:

  • Method body on a pair of braces, the realization of a particular operation;
  • The main method name when calling this method, you should consider naming specification
  • Stage methods we use are static (j static).

4.2 Method Invocation

 

 输出:welcome to hello world!

5, an example - the lesson practice

Requirements: define a called hello methods for teachers and greet output is: hello Teacher!

 

 Second, the use of

1, if the method does not contain parameters, but there is a return value, a method we call with no parameters return value

For example: in the case of FIG code defines a method named numberPlus, no parameters, but the method returns an int value of the operations performed to calculate the sum of two numbers, and returns the result

 

 In numberPlus () method, the return type is an int, return must be used in the method returns an integer value in the body.

Note 2, the return value of the method with a call, since the method will return a result of execution, and therefore generally receives its return value and the call processing method return value.

 

 3, can not be ignored

3.1、如果方法的返回类型为void,则方法中不能使用return返回值

3.2、方法的返回值最多只能一个,不能返回多个值

3.3、方法返回值的类型必须兼容,例如:如果返回值类型为int,则不能返回String类型的值

4、实例--课程练习

要求:定义一个名为calAvg的方法,用来计算两门课程成绩的平均值,并返回结果

原文链接:https://www.educoder.net/paths/54

Guess you like

Origin www.cnblogs.com/dxw-dong/p/12014460.html