1. 什么是JAVA方法
1.1 何谓方法
package com.axunla.mehtod;
public class Demo01 {
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(){
for (int i = 0; i <= 1000; i++) {
if (i%5==0){
System.out.print(i+"\t");
}
if (i%(5*3)==10 && i!=0){ //换行
System.out.println();
//System.out.print("\n");
}
}
}
}
2. 方法的定义及调用
2.1 方法的定义
2.2 方法的调用
package com.axunla.mehtod;
public class Demo02 {
public static void main(String[] args) {
int max = max(10, 20);
System.out.println(max);
}
//比大小
public static int max(int a,int b){
int result = 0;
if(a==b){
System.out.println("a==b");
return 0; //return也是终止方法
}
if(a>b) {
result = a;
}else {
result = b;
}
return result;
}
}
3. 方法的重载
package com.axunla.mehtod;
public class Demo03 {
public static void main(String[] args) {
int max = max(10, 20,30,40);
System.out.println(max);
}
public static double max(double num1,double num2){
double result = 0;
if(num1==num2){
System.out.println("a==b");
return 0;
}
if(num1>num2) {
result = num1;
}else {
result = num2;
}
return result;
}
public static int max(int num1,int num2,int num3){
int result = 0;
if(num1==num2){
System.out.println("a==b");
return 0;
}
if(num1>num2) {
result = num1;
}else {
result = num2;
}
return result;
}
public static int max(int num1,int num2,int num3,int num4){
int result = 0;
if(num1==num2){
System.out.println("a==b");
return 0;
}
if(num1>num2) {
result = num1;
}else {
result = num2;
}
return result;
}
}
4. 命令行传递参数
注:如果直接运行calss文件,需要找到包的路径去加载,否则执行不了
5. 可变参数
示例:
package com.axunla.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... i){
System.out.println(i[0]);
System.out.println(i[1]);
System.out.println(i[2]);
System.out.println(i[3]);
System.out.println(i[4]);
System.out.println(i[5]);
}
}
用可变参数找最大值:
package com.axunla.method;
public class Demo04_1 {
public static void main(String[] args) {
//调用可变参数的方法
printMax(34,3,3,2,56.5);
printMax(new double[]{1,2,3});
printMax(1,2,3,56,345.4,434.3);
}
public static void printMax(double... numbers) {
if(numbers.length == 0){
System.out.println("No argument passed");
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);
}
}
6. 递归(小计算)
package com.axunla.method;
public class Demo05 {
public static void main(String[] args) {
Demo05 test = new Demo05();
test.test();
}
//方法栈溢出,错误使用方法
public void test () {
test();
}
}
package com.axunla.method;
public class Demo06 {
//阶乘
//2! 2*1
//3! 3*2*1
//5! 5*4*3*2*1
public static void main(String[] args) {
System.out.println(f(5));
}
//5! 5*4*3*2*1
public static int f(int n){
if(n==1){
return 1;
}else {
return n*f(n-1);
}
}
}