Results 1 to 6 of 6
Thread: making method, repurposing
- 10-27-2011, 03:51 AM #1
Member
- Join Date
- Sep 2011
- Posts
- 54
- Rep Power
- 0
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?
Java Code:import java.util.Random; public class Chance extends Random{ public int flip(){ //I fill in blank here } }
I triedfor 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?Java Code:return nextInt(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.
- 10-27-2011, 04:00 AM #3
Senior Member
- Join Date
- Oct 2011
- Posts
- 106
- Rep Power
- 0
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
- 10-27-2011, 03:18 PM #5
Member
- Join Date
- Sep 2011
- Posts
- 54
- Rep Power
- 0
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
Similar Threads
-
Making a method exercise question
By katiebear128 in forum New To JavaReplies: 6Last Post: 10-01-2011, 08:48 PM -
making an exe from .jar
By ron2794 in forum NetBeansReplies: 3Last Post: 02-04-2011, 08:28 AM -
Need help making a GUI
By DrKilljoy in forum New To JavaReplies: 21Last Post: 07-15-2010, 03:44 AM -
Need help making .jar
By yoodidoo in forum EclipseReplies: 4Last Post: 08-03-2009, 08:57 PM -
How would I go about making something like this...
By split in forum New To JavaReplies: 3Last Post: 07-15-2009, 06:10 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks