making method, repurposing
Suppose we want to add a flip() method to the Chance class. This method should return, at random, either a 0 or a 1, where 0 stands for tails and 1 stands for heads. In the box provided below, code this method. Be sure to take advantage of the fact that Chance extends Random.
Hint: what Random class method call will produce values of either 0 or 1?
Code:
import java.util.Random;
public class Chance extends Random{
public int flip(){
//I fill in blank here
}
}
I tried for the fill-in-the-blank part, but it didn't work. I though that that method, from the Random class, generates a random integer between 0 and 1?
What am I doing wrong?
Re: making method, repurposing
Read the API for nextInt, the very first sentence of this method in fact -- you're close but not quite there in a very significant way. Also, there's another method of Random that is even more intuitive for your purposes.
Re: making method, repurposing
why don't you use a temp variable and if the random() method is equal to 0.1 to .5 you assign your temp variable a value of 0 and if it is .6 to .9 you assign a value of 1 to your temp variable. That or you might be able to use the floor or ceiling method depending on the value the random method returns.
Re: making method, repurposing
Quote:
Originally Posted by
mwr1976
why don't you use a temp variable and if the random() method is equal to 0.1 to .5 you assign your temp variable a value of 0 and if it is .6 to .9 you assign a value of 1 to your temp variable. That or you might be able to use the floor or ceiling method depending on the value the random method returns.
Because she is subclassing Random, and so there's no need for this as Random is quite capable of serving her purposes in a much simpler way.
Re: making method, repurposing
thanks furable, I figured it out. Turns out nextInt returns the parameter-1...so I actually needed nextInt(2).
I didn't see that other method that you mentioned might work though.
Re: making method, repurposing
Quote:
Originally Posted by
katiebear128
thanks furable, I figured it out. Turns out nextInt returns the parameter-1...so I actually needed nextInt(2).
I didn't see that other method that you mentioned might work though.
Yes, that's right, nextInt(2) will return 0 or 1 (think of the 2 as representing 2 possible return values). The other method is nextBoolean which returns either true or false, and so it's even more idiot-proof in this situation.