带返回值方法的定义格式

 1 package day05;
 2 
 3 public class MethodDemo04 {
 4     public static void main(String[] args) {
 5         /*带返回值方法的定义格式:
 6          * public static 数据类型 方法名(参数){
 7          *   return 数据;
 8          * }
 9          * 方法定义时return后面的返回值与方法定义上的数据类型要匹配,否则程序将报错
10          * 带返回值方法的调用格式:
11          * 数据类型 变量名 = 方法名(参数)
12          * */
13         int num = add(10, 20);
14         System.out.println(num);
15     }
16 
17     public static int add(int a, int b) {
18         int c = a + b;
19         return c;
20     }
21 }

执行结果:

eg:

 1 package day05;
 2 
 3 public class MethodDemo05 {
 4     public static void main(String[] args) {
 5         System.out.println(getMax(1, 9));
 6         int result = getMax(1, 9);
 7         for (int i = 1; i <= result; i++) {
 8             System.out.println("hello");
 9         }
10     }
11 
12     //方法可以获取两个数的最大值
13     public static int getMax(int a, int b) {
14         if (a > b) {
15             return a;
16         } else {
17             return b;
18         }
19     }
20 }

执行结果:

posted @ 2020-12-31 21:59  Eleanor123  阅读(201)  评论(0编辑  收藏  举报