简体   繁体   中英

Getting Exception in thread “main” java.lang.NullPointerException error

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?

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?

您需要实例化Random对象

Random rand = new Random();

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));
   }
}

谁来初始化您的rand

   static Random rand = new Random();

您必须在使用前初始化rand变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM