Source: http://www.imooc.com/code/1579
If the method does not contain a parameter, but has a return value, we call it a method with no parameter return value.
For example: The following code, which defines a method named Calsum, has no arguments, but the return value is of type int, performs an operation that calculates the sum of two numbers and returns the result
In the Calsum () method, the return value type is type int, so you must return an integer value using return in the method body.
When calling a method with a return value, it is important to note that because the method executes returns a result, the return value is generally received and processed when the return value method is called. Such as:
Operation Result:
"Small traps" that cannot be overlooked:
1. If the return type of the method is void, the return value cannot be used in the method!
2. The return value of a method can have at most one and cannot return multiple values
3, the type of the method return value must be compatible, for example, if the return value type is int, you cannot return a String value
Task
A method named Calcavg has been defined in the editor to calculate the average of two course scores and return the results.
Please complete the code in section 9, 15, and line, implement call Calcavg () method, and output the average score.
The result of the operation is:
1 Public classHelloWorld {2 3 Public Static voidMain (string[] args) {4 5 //To create an object named Hello6HelloWorld Hello =NewHelloWorld ();7 8 //Call the Calcavg () method of the Hello object and save the return value in the variable avg9 DoubleAVG =Ten OneSystem.out.println ("Average score:" +avg); A } - - //defines a method that returns a value of type double the PublicCalcavg () { - - Doublejava = 92.5; - Doublephp = 83.0; + DoubleAvg = (java + php)/2;//Calculate Average - + //return value using return A at - } -}
Myans:
1 Public classHelloWorld {2 3 Public Static voidMain (string[] args) {4 5 //To create an object named Hello6HelloWorld Hello =NewHelloWorld ();7 8 //Call the Calcavg () method of the Hello object and save the return value in the variable avg9 DoubleAVG =Hello.calcavg ();Ten OneSystem.out.println ("Average score:" +avg); A } - - //defines a method that returns a value of type double the Public DoubleCalcavg () { - - Doublejava = 92.5; - Doublephp = 83.0; + DoubleAvg = (java + php)/2;//Calculate Average - + //return value using return A returnavg; at - } -}
Mu class net-java first season -7-3 the use of a non-parametric return value method in Java