方法:
就是能完成特定功能的代码块。(其他语言中所说的函数)格式:
修饰符 返回值类型 方法名(参数类型 参数1,参数2,参数3...){
方法体语句;
return 返回值;
}
解析:
返回值类型:功能结果的数据类型
方法名:符合命名规则。
参数:
实际参数:实际参与运算的参数
形式参数:在方法定义的参数(用来接收传来的实际参数)
参数类型:就是数据类型
参数名: 变量名
方法体语句:完成功能的代码
return:结束方法
返回值:方法功能的结果,就是由return带给调用者。
1-返回值类型(结果的数据类型)
2-参数列表(要传递的参数个数,以及每个参数的类型)
注意:
1-方法不调用不会执行。
2-方法与方法是平级关系,不能嵌套定义方法。
3-方法定义时,参数之间用逗号隔开。
4-方法调用时不需要再传递数据类型。
5-如果方法有返回值类型,一定要有return返回结果。
案例解释:
求两个数据之和的案例
package com.lcn.day05;
public class FunctionDemo1 {
/**
* 求两个数据之和的案例
*/
public static void main(String[] args) {
int a = 10;
int b = 20;
//单独调用
sum(a,b);
//输出调用
System.out.println(sum(a,b));
//赋值调用
int result = sum(a,b);
//这里可以对result进行想要的操作
System.out.println(result);
}
public static int sum(int x,int y){
int c = x+y;
return c;
}
}
(在有参数的方法调用中应注意:)
1-单独调用:一般来说没有意义,不推荐(只适用void(无参)返回值类型)。2-输出调用:直接输出结果,无法对后期针对结果做操作
3-赋值调用,推荐使用
案例:
键盘输入三个数,输出其中的最大值:
package com.lcn.day05;
import java.util.Scanner;
public class FunctionDemo4 {
/**
* 返回三个数中的最大值
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数:");
int x = sc.nextInt();
System.out.println("请输入第二个数:");
int y = sc.nextInt();
System.out.println("请输入第三个数:");
int z = sc.nextInt();
int max = getMax(x,y,z);
System.out.println("最大数是:"+max);
}
方法一:
public static int getMax(int a,int b,int c){
if(a>b){
if(a>c){
return a;
}else{
return c;
}
}else if(b>c){
return b;
}else{
return c;
}
//-------------------------------------------
方法二:
if(a>b){
if(a>c){
return a;
}else{
return c;
}
}else{
if(b>c){
return b;
}else{
return c;
}
}
//-----------------------------------------
方法三:
if(a>b){
return (a>c?a:c);
}else{
return (b>c?b:c);
}
//------------------------------------------
方法四:
int max=(a>b?(a>c?a:c):(b>c?b:c));
return max;
方法五://上式改进
-
return (a>b?(a>c?a:c):(b>c?b:c));//从代码可读性来讲不建议使用
//--------------------------------------------
}
}