014-JAVA函数定义及return语句的使用

时间:2025-04-09 08:16:13
  • package T9;
  • //计算器
  • public class Calc {
  • /*
  • 函数(方法)括号里面的就是参数(局部变量)
  • * /
  • //1.无返回值无参数
  • public void display(){
  • ("无参数无返回值的函数");
  • }
  • //2.无返回值有参数
  • public void eat(String name) {
  • (name + "正在吃饭");
  • }
  • //多个参数之间用逗号分隔
  • public void eat(String name,String foodName){
  • (name + "正在吃" + foodName);
  • }
  • //3.有参数无返回值,求a+b的和
  • public void add(int a,int b) {
  • ("a+b=" + (a+b));
  • //结束函数运行
  • return;
  • }
  • //4.有参数有返回值,返回a+b+c的结果
  • public int add(int a,int b,int c){
  • return a+b+c;
  • }
  • //标志函数
  • public int flag(int x){
  • if(x>0)
  • return 1;
  • else if(x<0)
  • return -1;
  • //x=0时,运行该语句
  • return 0;
  • }
  • public static void main(String[] args) {
  • //定义类的变量(对象|实例),创建对象c,c代表Calc里面所有的成员变量,成员方法
  • Calc c = new Calc();
  • c.display();
  • ("张三");
  • ("张三","牛排");
  • c.add(3,5);
  • int sum = c.add(3,5,8);
  • ("sum=" + sum);
  • ("sum="+ c.add(9,8,7));
  • int y = (100);//x>0返回1
  • ("y=" + y);
  • y = (-1000); //x<0,返回-1
  • ("y=" + y);
  • y = (0); //x=0,返回0
  • ("y=" + y);
  • }
  • }
  • 相关文章