晚上,陪几个客户吃饭
教育局的
嗯.
____________________________________________开始学方法了...._________________朋友们,有错误帮忙指正啊.
_______________啊,楼主困了........................
如果不需要传递参数到方法中,只要将括号写出,不必填入任何内容。此外,如果方法没有返回值,则在返回值类型处要明确写出void,此时方法中的 return 语句可以省略。方法执行完后无论有无返回值都将回到方法的调用处并向下继续执行。
void 表示此方法没有返回值;
示例:
public class Test23{
public static void main(String args[]){
printIt();
printIt();
printIt();
System.out.println("Hello,World!");
}
public static void printIt(){
char arc[] = { 'H','e','l','l','o',',','h','3'};
for(int i = 0;i<arc.length;i++){
System.out.print( arc[i]);
}
System.out.println();
}
}
方法命名规则:第一个单词首字母小写,接下来的单词首字母大写;
如果需要一个方法有返回值,直接在返回值处写上返回值类型即可;
示例:
public class Test24{
public static void main(String args[]){ //主方法
int one = addOne(12,44); //方法的调用
float two = addTwo(13.2f,11.2f); //方法的调用
System.out.println("one 的值: " + one); //输出结果
System.out.println("two 的值: " + two); //输出结果
}
public static int addOne(int x,int y){ //定义返回值类型为 int 的方法计算两个值的和
int temp = 0; //方法中声明的变量为局部变量
temp = x + y;
return temp;
}
public static float addTwo(float x,float y){ //定义返回值类型为float的方法计算两个值的和
float temp = 0;
temp = x + y;
return temp;
}
}
方法的重载:就是方法名称相同,但参数的类型和参数的个数不周,能过传送参数的个数及类型不同以完成不同功能的方法调用.
public class Test25{
public static void main(String args[]){ //主方法
int one = add(12,44); //方法的调用
float two = add(13.2f,11.2f);
int three = add(10,20,39); //方法的调用
System.out.println("one 的值: " + one); //输出结果
System.out.println("two 的值: " + two); //输出结果
System.out.println("three 的值: " + three); //输出结果
}
public static int add(int x,int y){ //定义返回值类型为 int 的方法计算两个值的和
int temp = 0; //方法中声明的变量为局部变量
temp = x + y;
return temp;
}
public static float add(float x,float y){ //定义返回值类型为float的方法计算两个值的和
float temp = 0;
temp = x + y;
return temp;
}
public static int add(int x,int z,int y){ //定义返回值类型为 int 的方法计算三个值的和
int temp = 0; //方法中声明的变量为局部变量
temp = x + y + z;
return temp;
}
}
return 除了可以返回值外,还可以结束方法;
示例:
public class Test26{
public static void main(String args[]){
System.out.println("1----调用方法之前");
fun(10);
System.out.println("2----调用方法之后");
}
public static void fun(int i){
System.out.println("3----进入方法");
if(i==10){
return; //结束方法,并返回被调用处
}
System.out.println("4----正常执行完方法");
}
}
public class Test27{
public static void main(String arg[]){
int s = sum(100);
System.out.println("计算结果: " + s );
}
public static int sum(int i){
if(i==1){
return 1;
}else {
return i + sum(i-1);
}
}
}