Sound back with equal probability every time

I created a class in Java called Chick. Which contains three variables, a name and two sounds. I have a method called getSound () that will return either sound with equal probability every time. How do i do this?

My sample code is:

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;
    }     
} 

What change should I make in the getSound method? Please help me with a detailed answer. If you can write off the method with the proper requirements.

+4
source share
1 answer

The smallest change to your code to do this job:

public String getSound() {
    return Math.random() < .5 ? mySound : mySound2;
}

If you had a lot of sounds, I would use an array:

private String[] sounds = new String[10]; // eg 10 sounds

public String getSound() {
    return sounds[new Random().nextInt(sounds.length)];
}

Note that mathematically 2 can be considered “a lot”: the version of the array can be used for 2 sounds.


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)];
    }
}
+7

Source: https://habr.com/ru/post/1532400/


All Articles