我在Java中创建了一个名为Chick的类.其中包含三个变量,名称和两个声音.我有一个名为getSound()的方法,每次都会返回相同概率的声音.我该怎么做?
我的示例代码在这里:
class Chick implements Animal {
private String myType;
private String mySound;
private String mySound2;
public Chick(String type, String sound,String sound2)
{
myType = type;
mySound = sound;
mySound2=sound2;
}
public String getSound()
{
return mySound;
}
}
Run Code Online (Sandbox Code Playgroud)
我必须在getSound方法中做出哪些改变?请帮我详细解答.如果可以,请写下具有适当要求的方法.
对您的代码进行最小的更改将是:
public String getSound() {
return Math.random() < .5 ? mySound : mySound2;
}
Run Code Online (Sandbox Code Playgroud)
如果你有很多声音,我会使用一个数组:
private String[] sounds = new String[10]; // eg 10 sounds
public String getSound() {
return sounds[new Random().nextInt(sounds.length)];
}
Run Code Online (Sandbox Code Playgroud)
注意,在数学上2可以被认为是"很多":阵列版本可以用于2个声音.
对于灵活的解决方案,还可以在构造函数中使用varargs参数,允许任意数量的声音:
punic class Animal {
private final String[] sounds;
public Animal(String type, String... sounds) {
this.sounds = sounds;
}
public String getSound() {
return sounds[new Random().nextInt(sounds.length)];
}
}
Run Code Online (Sandbox Code Playgroud)