Java中Math类的使用
1.java.lang包中的Math类提供了一些用于数学计算的方法。
2.Math.random()该方法用于产生一个0到1区间的double类型的随机数,但是不包括1。
用Math.random()方法制作一个1-6的随机数游戏:
public class Text {
public static void main(String [] args){
int h = (int)(6*Math.random()+1);
System.out.println(h);
}
}
运行结果:
4
1
方法的重载(overload)
方法的重载是指一个类中可以定义多个方法名相同,但参数不同的方法。 调用时,会根据不同的参数自动匹配对应的方法。
构成方法重载的类型:
形参类型不同:
/* 求和的方法 /
public static int add(int n1, int n2) {
int sum = n1 + n2;
return sum;
}
// 方法名相同,参数类型不同,构成重载
public static double add(double n1, int n2) {
double sum = n1 + n2;
return sum;
}
形参个数不同:
/* 求和的方法 /
public static int add(int n1, int n2) {
int sum = n1 + n2;
return sum;
}
public static int add(int n1, int n2, int n3) {
int sum = n1 + n2 + n3;
return sum;
}
形参顺序不同:
/* 求和的方法 /
public static int add(int n1, int n2) {
int sum = n1 + n2;
return sum;
}
// 方法名相同,参数顺序不同,构成重载
public static double add(int n1, double n2) {
double sum = n1 + n2;
return sum;
}
注意:
重载的方法,实际是完全不同的方法,只是名称相同而已!
只有返回值不同,不构成方法的重载,如:
/* 求和的方法 /
public static int add(int n1, int n2) {
int sum = n1 + n2;
return sum;
}
public static double add(int n1, int n2) {
double sum = n1 + n2;
return sum;
}
只有参数名称不同,也不构成方法的重载
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。