Java方法
2021/6/13 20:21:28
本文主要是介绍Java方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Java方法
方法的定义
package com.zhang.method; public class Demo01 { public static void main(String[] args) { int sum = add(1,2); System.out.println(sum); num(2,50); } // 加法 public static int add(int a,int b){ return a+b; } //打印5的倍数 public static void num(int a,int b){ for(int i=a;i<=b;i++){ if(i%5==0) System.out.print(i+"\t"); if((i%(5*3))==0) System.out.println(); } } }
方法调用
package com.zhang.method; public class Demo02 { public static void main(String[] args) { double result=max(15,15.5); System.out.println(result); } //比大小 形参 public static double max(double a,double b){ double result=0; result=a>b?a:b; if(a==b) result = a; return result; } }
方法的重载
就是同名 不同形参的方法。
package com.zhang.method; public class Demo03 { public static void main(String[] args) { double sum = add(5.5,6.4); System.out.println(sum); } 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(double a,double b) { return a + b; } }
命令行传参
package com.zhang.method; public class Demo04 { public static void main(String[] args) { for (int i =0;i< args.length;i++){ System.out.println(args[i]); } } }
命令行执行要找到包的位置
可变参数
不定向参数
package com.zhang.method; public class Demo05 { public static void main(String[] args) { Demo05 d5 = new Demo05(); d5.test(1,3,4,5); } public void test (int ... i){ //可变长数组 System.out.println(i[2]); } }
package com.zhang.method; public class Demo06 { public static void main(String[] args) { Demo06 d6 = new Demo06(); double m1 = d6.max(1,25,56,85.4,2.3); double m2 = d6.max(50,20,1.5,3.2,12.3655,54.1); System.out.println(m1); System.out.println(m2); } public double max(double ... i){ //可变长数组,必须写在形参的最后 double result=0; if (i.length==0){ System.out.println("输入错误!"); return 0; } result=i[0]; for (int a=1;a<i.length;a++){ if (i[a]>result) result = i[a]; } return result; } }
递归
package com.zhang.method; public class Demo08 { public static void main(String[] args) { System.out.println(fun(3)); } public static int fun(int n){ if (n==1) { return 1; }else { return n*fun(n-1); } } }
这篇关于Java方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南