方法(也叫函数)
方法就是完成特定功能的代码块
方法格式:
修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2…) {
函数体;
return 返回值;
}
方法的两个明确:
* A:返回值类型 明确功能结果的数据类型
* B:参数列表 明确有几个参数,以及参数的类型
练习:求两个数的和
public class MethodDemo {
/*
* 写一个方法,用于求和。 两个明确: 返回值类型 int 参数列表 int a,int b
*/
public static int sum(int a, int b) {
// int c = a + b;
// return c;
return a + b;
}
public static void main(String[] args) {
// 单独调用
// sum(10,20);
// 输出调用
// System.out.println(sum(10,20));
// 赋值调用
int s = sum(10, 20);
// s+=100;
System.out.println("s:"+s);
}
}
联系:键盘录入两个数据,返回两个数中的较大值
import java.util.Scanner;
/*
* 需求:键盘录入两个数据,返回两个数中的较大值
*
* 两个明确:
* 返回值类型:int
* 参数列表:int a,int b
*/
public class MethodTest {
// 返回两个数中的较大值
public s