方法的四种样式:
无参无返;
无参有返;
有参无返;
有参有返;
public class MethodDefine {
public static void main(String[] args) {
//方法的调用
method1();
int result = method2();
System.out.println("a与b的和是:" + result);
method3(1,2);
int sum = method4(1,2);
System.out.println("a与b的和是:" + sum);
}
//无参无返
public static void method1(){
int a = 1;
int b = 2;
int sum = a + b;
System.out.println("a与b的和是:" + sum);
}
//无参有返
public static int method2(){
int a = 1;
int b = 2;
int sum = a + b;
return sum;
}
//有参无返
public static void method3(int a, int b){
int sum = a + b;
System.out.println("a与b的和是:" + sum);
}
//有参有返
public static int method4(int a, int b){
int sum = a + b;
return sum;
}
}
练习:定义一个方法,求出1~100之间整数的累加和
public class Demo02MethodSum {
public static void main(String[] args) {
System.out.println("1-100的累加和是:" + getSum());
}
public static int getSum() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
return sum;
}
}