
今天进行了方法参数和多参数方法的学习,觉得和C语言函数中形参和实参类似,记录一下
2.4 方法参数
先看一下这个代码
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+"】");
}
}
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+"】");
}
}