java方法的声明及使用

来源:互联网 发布:淘宝买家提问怎么删除 编辑:程序博客网 时间:2024/05/25 12:20

方法的格式

public static 返回值类型 方法名称(类型 参数1,类型 参数2,..){

程序语句;

[return 表达式];

}

public class Test{

public static void main(String[]args){

int one =addOne(10,20);     //调用整数的加法操作

float two = addTwo(10.3f,13.3f);   //调用浮点数的加法操作

  System.out.println(one);

System.out.println(two);

}

public static int addOne(int x,int y){     //定义方法  主函数调用的需要加上public static

int temp = 0;     //temp为局部变量,只在此方法中有效

temp=x+y;

return temp;

 }

public static float addTwo(float x,float y){

float temp = 0;

temp=x+y;

return temp;

}

递归调用

public class Test{

public static void main(String[]args){

System.out.println(sum(100));

}

public static int sum(int num){

if(num==1){

return 1;

}

else{

return num+sum(num-1);

}

}

}

0 0