方法
方法的定义和调用
//static 是静态的 调用的话可以直接调用
public static void 方法名(){
//代码块
}
public static 数据类型 方法名(){
//代码块
}
public static 数据类型 方法名(数据类型 形参){
//代码块
}
方法的调用
调用不带参数的方法
public class demo {
public static void main(String[] args) {
//调用方法
add();
}
public static void add(){
String blog = "https://likedx.com";
System.out.println("My blog " + blog);
}
}
调用带参数的方法
public class demo {
public static void main(String[] args) {
int show = show(10, 20);
System.out.println(show);
}
//这个a,b是形参
public static int show(int a, int b){
return a+b;
}
}
方法带参求最大值
public class demo {
public static void main(String[] args) {
System.out.println("最大的值是:" + add(60, 50));
}
public static int add(int a, int b){
int max = 0;
if (a == b){
return 0;
} else if (a > b) {
max = a;
} else if (a < b) {
max = b;
}
return max;
}
}
用三元运算符求最大值
public class demo {
public static void main(String[] args) {
add(10,20);
}
public static void add(int a,int b){
System.out.println(a > b ? a:b);
}
}
利用方法遍历数组
public class demo {
public static void main(String[] args) {
int [] arr = {10,20,30};
printArr(arr);
}
//遍历数组的方法
public static void printArr(int [] arr){
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
方法的值传递
public class demo {
public static void main(String[] args) {
int a = 10;
//这里打印的a是实参
System.out.println(a); //10
//这里调用的a是形参
add(a); //20
}
public static void add(int a) {
a = 20;
System.out.println(a);
}
}
方法的重载
public class demo {
/*
* 方法重载:
* 方法名必须一样 形参不能相同
* 方法返回的类型可以相同也可以不同
*/
public static void main(String[] args) {
int add = add(10, 20);
int add1 = add(10, 20, 30);
System.out.println(add);
System.out.println(add(10,0.5));
}
public static int add(int a,int b) {
return a+b;
}
public static int add(int a,int b,int c){
return a+b+c;
}
public static double add(int a,double b) {
return a+b;
}
}
方法的递归
public class demo {
/*
* 1! = 1*1
* 2! = 2*1*1
* 3! = 3*2*1
* 4! = 4*3*2*1
* 5! = 5*4*3*2*1
*/
public static void main(String[] args) {
int show = show(3);
System.out.println(show);
}
public static int show(int number){
if (number == 1) {
return 1;
}else {
/*
* 6 * (6-1)
* 6 * (5-1)
* 6 * (4-1)
* 6 * (3-1)
* 6 * (2-1)
*/
return number*show(number-1);
}
}
}
One comment
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com