35 Java语言基础方法概述和格式说明
为什么要方法
提高代码的复用性
什么是方法
完成特定功能的代码
方法的格式
修辞符 返回值类型 方法名(参数类型 参数名1; 参数类型 参数名2...){
方法体语句;
return返回结果;
}
方法格式化说明
修饰符
返回值类型 就是功能结果的数据类型
方法名 符合命名规则即可 方便我们调用
参数 实际 参数 就是实际参与运算的
形式参数 就是方法定义上的 用于接收定义参数 的
参数类型
就是参数的数据类型
参数名
就是变量名
方法体语句
就是完成功能的代码
return
结束方法
返回值
就是功能的结果 ,由return带给调用者
1 public class Add9 { 2 3 public static int add(int a, int b){ // 参数,变量,方法都要指定类型 4 int sum = a+b; 5 return sum; 6 7 } 8 9 public static void main(String[] args) { //void 不返回任何值 10 11 System.out.println(add(1,2)); 12 } 13 }
方法调用
方法不调用不执行
方法与方法是平级关系 不能嵌套定义
方法定义的时候参数之间是用逗号隔开的
方法调用的时候不用再传递数据类型
如果方法有明确的返回值,一定要有return带加一个值
1 public class Great { 2 public static void great(int a, int b){ 3 if(a>b){ 4 System.out.println("a>b"); 5 6 }else{ 7 System.out.println("a<b"); 8 } 9 } 10 11 public static void main(String[] args) { 12 great(1,2); 13 } 14 }
指定行和列的星星
public class Demo3_Method { public static void creat_star(int x,int y){ for (int i = 0; i <=x ; i++) { for (int j = 0; j <y ; j++) { System.out.print("*"); } System.out.println(""); } } public static void main(String[] args) { creat_star(8,5); } }