慕课网-Java入门第一季-7-3 Java 中无参带返回值方法的使用

来源:http://www.imooc.com/code/1579

如果方法不包含参数,但有返回值,我们称为无参带返回值的方法。

例如:下面的代码,定义了一个方法名为 calSum ,无参数,但返回值为 int 类型的方法,执行的操作为计算两数之和,并返回结果

在 calSum( ) 方法中,返回值类型为 int 类型,因此在方法体中必须使用 return 返回一个整数值。

调用带返回值的方法时需要注意,由于方法执行后会返回一个结果,因此在调用带返回值方法时一般都会接收其返回值并进行处理。如:

运行结果:

不容忽视的“小陷阱”:

1、 如果方法的返回类型为 void ,则方法中不能使用 return 返回值!

2、 方法的返回值最多只能有一个,不能返回多个值

3、 方法返回值的类型必须兼容,例如,如果返回值类型为 int ,则不能返回 String 型值

任务

在编辑器中已经定义了一个名为 calcAvg 的方法,用来计算两门课程成绩的平均值,并返回结果。

请在第 9、15、22 行中将代码填写完整,实现调用 calcAvg( ) 方法,并输出平均成绩。

运行结果为:

 1 public class HelloWorld {
 2     
 3     public static void main(String[] args) {
 4         
 5         // 创建名为hello的对象
 6         HelloWorld hello = new HelloWorld();
 7         
 8         // 调用hello对象的calcAvg()方法,并将返回值保存在变量avg中
 9         double avg = 
10         
11         System.out.println("平均成绩为:" + avg);
12     }
13 
14     // 定义一个返回值为double类型的方法
15     public          calcAvg() {
16         
17         double java = 92.5;
18         double php = 83.0;
19         double avg = (java + php) / 2; // 计算平均值
20         
21         // 使用return返回值
22         
23         
24     }
25 }


myans:

 1 public class HelloWorld {
 2     
 3     public static void main(String[] args) {
 4         
 5         // 创建名为hello的对象
 6         HelloWorld hello = new HelloWorld();
 7         
 8         // 调用hello对象的calcAvg()方法,并将返回值保存在变量avg中
 9         double avg = hello.calcAvg();
10         
11         System.out.println("平均成绩为:" + avg);
12     }
13 
14     // 定义一个返回值为double类型的方法
15     public double calcAvg() {
16         
17         double java = 92.5;
18         double php = 83.0;
19         double avg = (java + php) / 2; // 计算平均值
20         
21         // 使用return返回值
22         return avg;
23         
24     }
25 }
原文地址:https://www.cnblogs.com/chenliting/p/3969746.html