java方法概念
package com.liu.method;
public class Demo01 {
//main方法
public static void main(String[] args) {
int sum = add(1, 2);
System.out.println(sum);
test();
}
//加法
public static int add(int a,int b){
return a+b;
}
public static void test(){
int num = 0;
for (int i = 1; i <= 1000; i++) {
if(i % 5 == 0){
num++;
System.out.print(i + " ");
if(i % (5*3) == 0){
System.out.println();
}
}
}
}
}
方法调用:
![image-20210128111018679](https://gitee.com/guyebai/cloudimage/raw/master/img/image-20210128111018679.png)
![image-20210128114348538](https://i-blog.csdnimg.cn/blog_migrate/ef8c7924b4c6f2d268498a16b3b0f1be.png)
package com.liu.method;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
int max = compare(10, 20);
System.out.println(max);
}
//比大小
public static int compare(int a, int b) {
int result = -1;
if (a == b){
System.out.println("a == b");
return 0; //终止方法
}
if (a > b) {
result = a;
} else {
result = b;
}
return result;
}
}
java都是值传递。
方法重载
![image-20210128115506282](https://i-blog.csdnimg.cn/blog_migrate/a53f0aa9f276f142eaf44b59d4b428e8.png)
public void method(){}
public void method(int i){}
public void method(int a, int b){}
public void method(int a, double b){}
命令行传递参数
![image-20210128115746536](https://i-blog.csdnimg.cn/blog_migrate/fb1a4f605eeff4208a4f3e0f7edaf441.png)
运行一个java文件,要找到它的包的路径,因此要回到src.
可变参数
![image-20210128122857242](https://i-blog.csdnimg.cn/blog_migrate/a291fc749b4b745057bdf7580b13d329.png)
ackage com.liu.method;
public class Demo04 {
public static void main(String[] args) {
Demo04 demo04 = new Demo04();
demo04.test(1,2,3,4,5,6);
}
public void test(int x, int... i){
System.out.println(x + i[2]);
System.out.println(x + i[3]);
System.out.println(x + i[4]);
System.out.println(x + i[1]);
}
}
递归
Exception in thread “main” java.lang.StackOverflowError—栈溢出error
package com.liu.method;
public class Demo05 {
public static void main(String[] args) {
Demo05 demo05 = new Demo05();
demo05.test();
}
public void test(){
test();
}
// Exception in thread "main" java.lang.StackOverflowError
}
package com.liu.method;
public class Demo06 {
public static void main(String[] args) {
int result = f(5);
System.out.println(result);
}
public static int f(int n){
if(n==1){
return 1;
}else {
return n*f(n-1);
}
}
}
边界条件:边界
前阶段
返回阶段:n*(n-1)
栈机制:底层main, f往上
基数比较小才能用,大基数最好不要用递归。