Java programming those things 53-method declaration example Zhengzhou game college Chen yuefeng from: http://blog.csdn.net/mailbomb
7.3 method declaration exampleThe method implements a function. When declaring a method, you must not only determine the access control operator, modifier, return value type, method, and parameter list as needed, the code of the method body is also implemented according to the functional logic. In actual settings, You must select the most appropriate content based on the function structure. The following uses a series of examples to demonstrate how to select and set.
7.3.1 determine whether an integer is an even numberFunction requirements: judge whether an integer is an even number. Simple Analysis: To determine any integer, You need to input an integer from the outside during the judgment. During method declaration, you must declare this Integer as a parameter. The result is an even number or not even number. There are only two States. You can use data types that can represent two States. The most intuitive type is boolean. The code for implementation of this method is as follows: public Boolean iseven (int n) {return n % 2 = 0;} According to logic needs, select public as the Access Controller and leave the modifier blank, the return value type is Boolean, and an integer parameter is input to the parameter list, so that the structure of the method declaration is completed. For an even number, you only need to determine whether the remainder is zero. If the remainder is zero, the result is true. Otherwise, the value of the comparison expression is directly returned as the return value of the method.
7.3.2 array sortingFunctional requirements: Simple Analysis of sorting of integer array data from small to large (ascending): to achieve universality, you need to pass the array to be sorted into the method each time, therefore, an integer array parameter is required in the method declaration. In order to be intuitive, the sorted array can be returned. NOTE: With the subsequent study, this return value is not required. The code for implementing this method is as follows: public int [] bubblesort (INT [] m) {for (INT I = 0; I <m. length-1; I ++) {for (Int J = 0; j <m. length-1-I; j ++) {If (M [J]> M [J + 1]) {int temp = m [J]; M [J] = m [J + 1]; m [J + 1] = temp ;}} return M ;}inside the method, use the Bubble Method to sort the array, and finally return the sorted array as the return value. In actual use, the array can be considered as a common data type, the return value of the method, and the type in the parameter list.