Results 1 to 4 of 4
  1. #1
    keo
    keo is offline Member
    Join Date
    May 2010
    Posts
    34
    Rep Power
    0

    Default 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:

    Java Code:
    //Variables
    private boolean field;
    private Random rnd
    
    //Constructor
    field = rnd nextBoolean();
    Which returns a NullPointerException. Help please!

  2. #2
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    You did not create a new Random object to use (using new Random(....)). You are trying to use a blank (null) rand object.

  3. #3
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Also, the easiest way to make a random boolean is this:
    Java Code:
    boolean b = (Math.random() < .5);
    And there you have it, a 50-50 chance for true or false.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  4. #4
    keo
    keo is offline Member
    Join Date
    May 2010
    Posts
    34
    Rep Power
    0

Similar Threads

  1. Replies: 14
    Last Post: 10-19-2009, 10:57 AM
  2. Replies: 8
    Last Post: 04-19-2009, 05:50 PM
  3. random numbers without random class`
    By carlos123 in forum New To Java
    Replies: 4
    Last Post: 01-17-2008, 10:44 PM
  4. Replies: 0
    Last Post: 12-19-2007, 09:10 AM
  5. Replies: 0
    Last Post: 12-19-2007, 09:01 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •