Results 1 to 4 of 4
Thread: random boolean in Constructor
- 05-24-2010, 06:04 AM #1
Member
- Join Date
- May 2010
- Posts
- 34
- Rep Power
- 0
random boolean in Constructor
When I make a new object, I want the constructor to randomly make a field true OR false.
I've imported the util (import java.util.Random;)
I've attempted to do stuff like this:
Which returns a NullPointerException. Help please!Java Code://Variables private boolean field; private Random rnd //Constructor field = rnd nextBoolean();
- 05-24-2010, 06:38 AM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
You did not create a new Random object to use (using new Random(....)). You are trying to use a blank (null) rand object.
- 05-24-2010, 07:13 AM #3
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
Also, the easiest way to make a random boolean is this:
And there you have it, a 50-50 chance for true or false.Java Code:boolean b = (Math.random() < .5);
Ever seen a dog chase its tail? Now that's an infinite loop.
- 05-24-2010, 07:13 AM #4
Member
- Join Date
- May 2010
- Posts
- 34
- Rep Power
- 0
Similar Threads
-
how i use the random class to random the cards i have
By yanipao in forum New To JavaReplies: 14Last Post: 10-19-2009, 10:57 AM -
How do I generate random numbers in a certain range using the random class?
By frasifrasi in forum New To JavaReplies: 8Last Post: 04-19-2009, 05:50 PM -
random numbers without random class`
By carlos123 in forum New To JavaReplies: 4Last Post: 01-17-2008, 10:44 PM -
Calling constructor of parent class from a constructor
By Java Tip in forum Java TipReplies: 0Last Post: 12-19-2007, 09:10 AM -
Calling constructor of same class from a constructor
By Java Tip in forum Java TipReplies: 0Last Post: 12-19-2007, 09:01 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks