1

I am writing a small java code to generate random values:

    import java.util.Random;
    public class Rann {
       static Random rand;
       public static void main(String args[]){
           int i;
           for(i=0;i<15;i++)
               System.out.println(rand.nextInt(7));
       }
    }

This gives an error:

Exception in thread "main" java.lang.NullPointerException
at Rann.main(Rann.java:7)

Any help would be highly appreciated. And is this the preferred way to generate random values in LeJOS?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Monty Swanson
  • 695
  • 16
  • 41

5 Answers5

5

you haven't initialized your random object

static Random rand = new Random(System.currentTimeMillis());

For best way to generate random numbers you can take a look at How do I generate random integers within a specific range in Java?

Community
  • 1
  • 1
mmounirou
  • 719
  • 6
  • 12
4

You need to instantiate the Random object

Random rand = new Random();
Kevin Le - Khnle
  • 10,579
  • 11
  • 54
  • 80
4

Try this. You forgot to tell it to make a new Random-Class object.

package foso;
import java.util.Random;
public class FoSo {
   static Random rand = new Random();
   public static void main(String args[]){
       int i;
       for(i=0;i<15;i++)
           System.out.println(rand.nextInt(7));
   }
}
Bry6n
  • 1,879
  • 1
  • 12
  • 20
3

Who will initialize your rand?

   static Random rand = new Random();
adarshr
  • 61,315
  • 23
  • 138
  • 167
3

You have to initialize your randvariable before using it.

juergen d
  • 201,996
  • 37
  • 293
  • 362