zoukankan      html  css  js  c++  java
  • 慕课网-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 }
  • 相关阅读:
    手动在本机仓库中放置jar包以解决Maven中央仓库不存在该资源的问题
    同一套代码部署到两台机器上,只有一台机器上的页面中文乱码
    Nginx与httpd共存
    [Z3001] connection to database 'zabbix' failed: [2003] Can't connect to MySQL server on 'x.x.x.x' (13)
    Excel中时间戳转换公式及原理
    springcloud服务注册和发现
    spingboot和springcloud简记
    postgres use
    访问者模式
    uml类图详解
  • 原文地址:https://www.cnblogs.com/chenliting/p/3969746.html
Copyright © 2011-2022 走看看