java 程序中的一个小问题。

来源:百度知道 编辑:UC知道 时间:2024/05/22 11:06:24
class Animal{

void cry(){

}
}

class Dog extends Animal{

void cry(){
System.out.println("汪汪");
}
}

class Cat extends Animal{

void cry(){
System.out.println("喵喵");
}
}

class Example{

public static void main(String args[]){

Animal am;
if(Math.random()>=0.5){
am=new Dog();
am.cry();
}
else{
am=new Cat();
am.cry();
}
}
}

问题:判断 if(Math.random()>=0.5) 是什么意思?

Math?

random是随即生成?

请达人用术语帮我解释一下这句话的意思...希望可以详细,易懂些。

例如 类 b=new 类(); //实例化对象b
b.f(1,2); //调用对象b的f方法并传参

Ps:虽然是个小问题,但小弟会及时采纳答案,麻烦大家了。

Math.random()>=0.5 的解释:在java.lang包下有一个Math类,Math类有一个方法是random(),通过Math.random()方法产生0-1之间的随机数。
通过上面的判断 am有一半的可能是猫的实例一半可能是狗的实例

if(Math.random()>=0.5) //判断产生的随机数是否大与等与0.5