Math 类位于 java.lang 包中,包含用于执行基本数学运算的方法, Math 类的所有方法都是静态方法,所以使用该类中的方法时,可以直接使用类名.方法名,如: Math.round();
常用的方法:
通过案例我们来认识一下他们的使用吧!!
运行结果:
PS: Math 类还提供了许多其他方法,可以注意关注 wiki ,查阅更多信息
public class HelloWorld {
public static void main(String[] args) {
// 定义一个整型数组,长度为10
int[] nums = new int[10];
//通过循环给数组赋值
for (int i = 0; i < nums.length; i++) {
// 产生10以内的随机数
int x = (int) (Math.random() * 10);
nums[i] = x;// 为元素赋值
}
// 使用foreach循环输出数组中的元素
for ( int num : nums ) {
System.out.print(num + " ");
}
}
}
这就是Math方法的random()方法的作用,随机产生