黑马程序员———方法的实现

来源:互联网 发布:unity3d c 基础教程 编辑:程序博客网 时间:2024/05/21 22:56

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

l什么是函数?
函数就是定义在类中的具有特定功能的一段独立小程序。
函数也称为方法。
l函数的格式:
修饰符 返回值类型 函数名(参数类型 形式参数1,参数类型 形式参数2,)

  {

  执行语句;

  return 返回值;

  }

  返回值类型:函数运行后的结果的数据类型。

  参数类型:是形式参数的数据类型。

  形式参数:是一个变量,用于存储调用函数时传递给函数的实际参数。

  实际参数:传递给形式参数的具体数值。

  return:用于结束函数。

  返回值:该值会返回给调用者。

示例:

package practice;
import java.util.Scanner;
public class ArrayDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub

showMax(getMax(inArr()));//最内层,调用inArry()方法,向数组中写入元素,中层得到数组中的最大值,外层输出数组中 的最大值。
}

//向数组中写入元素
public static int[] inArr() {
int[] newarr = new int[5];
for (int i = 0; i < newarr.length; i++) {
Scanner in = new Scanner(System.in);
newarr[i] = in.nextInt();
}
return newarr;
}
//得到数组中的最大值
public static int getMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
//打印数组中的最大值
public static void showMax(int Max) {
int showmax = Max;
System.out.println(showmax);
}
}


0 0