Day05__方法
作者:互联网
方法
何为方法?
package method;
//何为方法?
public class Demo01 {
public static void main(String[] args) {
System.out.println(add(1,2));
}
//加法
public static int add(int num1 ,int num2){
return num1+num2;
}
}
方法的定义和调用
package method;
public class Demo02 {
public static void main(String[] args) {
System.out.println(max(66,66));
}
//比大小
public static int max(int num1,int num2){
int result;
if(num1>num2){
result = num1;
} else if (num1<num2) {
result = num2;
}else{
System.out.println("相等");
return 0;
}
return result;
}
}
方法重载
package method;
public class Demo02 {
public static void main(String[] args) {
int num1 = max(10,20);
double num2 = max(1.1,2.2);
System.out.print(num1+","+num2);
}
//比大小
public static int max(int num1,int num2){
int result;
if(num1>num2){
result = num1;
} else if (num1<num2) {
result = num2;
}else{
System.out.println("相等");
return 0;
}
return result;
}
//比大小
public static double max(double num1,double num2){
double result;
if(num1>num2){
result = num1;
} else if (num1<num2) {
result = num2;
}else{
System.out.println("相等");
return 0;
}
return result;
}
}
命令行传参
package method;
//命令行传参
public class Demo03 {
public static void main(String[] args) {
//args.length 数组长度
for (int i=0 ; i<args.length ; i++){
System.out.println("args["+i+"]:"+args[i]);
}
}
}
可变参数
package method;
//可变参数
public class Demo04 {
public static void main(String[] args) {
Demo04 demo04 = new Demo04();
demo04.test();
//调用可变参数的方法
printMax(32,33,14,4,41);
printMax(new double[]{1,2,3,4,5});
}
public void test(int... i){
System.out.println(i);
}
public static void printMax(double... numbers){
if (numbers.length == 0){
System.out.println("No argument oassed");
return;
}
double result = numbers[0];
for(int i=1 ; i<numbers.length ; i++){
if(numbers[i]>result){
result = numbers[i];
}
}
System.out.println("The max value is " + result);
}
}
递归
package method;
//递归
public class Demo05 {
public static void main(String[] args) {
System.out.println(test(5));
}
//阶乘
public static int test(int n){
if (n==1){
return 1;
}else {
return n*test(n-1);
}
}
}
标签:__,num1,num2,int,Day05,static,result,方法,public 来源: https://www.cnblogs.com/lyc2001/p/16655124.html