Java中方法参数和多参数方法
2021/8/11 20:06:37
本文主要是介绍Java中方法参数和多参数方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
今天进行了方法参数和多参数方法的学习,觉得和C语言函数中形参和实参类似,记录一下
2.4 方法参数
先看一下这个代码
1 public class Custom { 2 3 public static void main(String[] args) { 4 random(); 5 code(); 6 } 7 8 /** 9 *生成6位随机数 10 */ 11 public static void random(){ 12 int code = (int) ((Math.random()+1) * 100000); 13 System.out.println(code); 14 } 15 16 /** 17 *生成4位随机数 18 */ 19 public static void code(){ 20 int code = (int) ((Math.random()+1) * 1000); 21 System.out.println(code); 22 } 23 24 }
观察可以发现,random和code代码其实没有太大的区别,只有*100000和*1000这个行为的区别。
为了解决这个问题,引入一个概念,那就是方法参数,我们可以把100000和1000这个数字定义为一个int类型的变量,然后赋不同的值,通过方法参数传递过去就能解决了。直接上代码:
public class Custom { public static void main(String[] args) { random(100000); random(1000); } /** *生成随机数 */ public static void random(int length){ int code = (int) ((Math.random()+1) * length); System.out.println(code); } }
实际上方法参数和声明变量并无区别,只是这个变量是要定义在方法参数这个位置里,编程语言里把这个声明的变量叫做形参
方法调用
如果有了参数声明后,就必须要传入参数, 这个参数可以是变量也可以是值,只是要注意数据类型要匹配,编程语言把这个传递的变量称为实参
// 直接传值 random(100000); // 传递变量 int len = 100000; random(len);
2.5 多参数方法
先来看一串代码
public class MessageCode { public static void main(String[] args) { code(1000); } public static void code(int len){ int code = (int)((Math.random()+1)*len); System.out.println("亲爱的用户,你本次的验证码是【"+code+"】"); } }
在实际工作当中,文案部分经常会被调整,如果每次都要修改方法内容,那么就会导致复用以及维护成本变高,所以我们会把文案也定义成变量。
在这个场景下,我们就需要定义多个参数了,看一下下边的这段代码
public class MessageCode { public static void main(String[] args) { String text = "亲爱的用户,你本次的验证码是"; code(text,1000); } public static void code(String text,int len){ int code = (int)((Math.random()+1)*len); System.out.println(text+"【"+code+"】"); } }
注意多个形参之间用逗号隔开。
附加:继续死磕一下随机数的产生,运行几遍后会发现,其实第一位并不随机,因为我们的第一位永远是1,那么就需要让Math.random的结果*9+1来实现
public class MessageCode { public static void main(String[] args) { String text = "亲爱的用户,你本次的验证码是"; code(text,1000); } public static void code(String text,int len){ int code = (int)(((Math.random()*9)+1)*len); System.out.println(text+"【"+code+"】"); } }
这篇关于Java中方法参数和多参数方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 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 实现数据请求