Results 1 to 3 of 3
  1. #1
    dario3004 is offline Member
    Join Date
    May 2010
    Posts
    2
    Rep Power
    0

    Default Random nextInt(int n) keeps throwing NullPointerException

    Hello!
    I'm doing a simple class and this is PART of the code:
    Java Code:
    	public void run(){
                  	Random generator;
    		while(true){
    			misura();
    			int c = generator.nextInt(2);
    			try {Thread.sleep(500);} catch (InterruptedException e){};
    			if (c == 0){
    				cpu.positivo(id);
    				System.out.println("Sensore "+ id +" positivo");
    			}
    			if (c == 1){
    				cpu.negativo(id);
    				System.out.println("Sensore "+ id +" negativo");
    			}
    		}
    	}

    When I start the thread, it tells me that this line threw a NullPointerException:
    Java Code:
    int c = generator.nextInt(2);

    What I am doing wrong?
    Thanks in advance :)

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    A NPE means that you're trying to access a field or method of an object that has never been initialized, that is null. So you must ask yourself, where in this code do you initialize the generator object?

    By the way, welcome to the forum!

  3. #3
    dario3004 is offline Member
    Join Date
    May 2010
    Posts
    2
    Rep Power
    0

    Default

    thankyou man!

    I simply fixed it creating the Random object when I declared it:
    Java Code:
    Random generator = new Random()
    :rolleyes: sorry for the newb mistake

Similar Threads

  1. nextInt(unknown source)
    By babyburger in forum New To Java
    Replies: 3
    Last Post: 03-18-2010, 04:03 PM
  2. Replies: 4
    Last Post: 08-30-2009, 11:22 AM
  3. Replies: 8
    Last Post: 04-19-2009, 05:50 PM
  4. throwing bug value
    By Dangi in forum New To Java
    Replies: 3
    Last Post: 10-25-2008, 06:14 AM
  5. throwing Exception
    By bugger in forum New To Java
    Replies: 3
    Last Post: 11-09-2007, 09:35 PM

Posting Permissions

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