2013-06-21 79 views
0

我想在surfaceView上生成10个随机位置来绘制10个圆圈。 下面的代码为x和y坐标分配了一个随机的浮点值,但我一直在随机值赋值上收到一个空指针异常,并且无法找出原因。android随机float返回null

rndX = new float[10]; 
rndY = new float[10]; 

for(int i=0;i<rndX.length;i++) 
{ 
    //get random x and y values 
    rndX[i] = (float)generator.nextInt(surface.getWidth()); 
    rndY[i] = (float)generator.nextInt(surface.getHeight()); 
} 
+0

检查恒 –

+0

行会,我会尽力的 – Zachary

+0

设置常数工作,是否意味着表面并没有在这一点上EEN产生的? – Zachary

回答

1

以下工作就好了。

float[] rndX = new float[10]; 
    float[] rndY = new float[10]; 

    int width = 100; 
    int height = 100; 

    Random generator = new Random(System.currentTimeMillis()); 

    for(int i=0;i<rndX.length;i++){ 
     rndX[i] = (float)generator.nextInt(width); 
     rndY[i] = (float)generator.nextInt(height); 
    } 

是什么原因造成您的NullPointerException可能是surfacegenerator变量,一个是不会被初始化。

1

你为什么不尝试:在表面方法

Random rand = new Random(); 

rndX = new float[10]; 
rndY = new float[10]; 

for(int i=0;i<10;i++) 
{ 
    //get random x and y values 
    rndX[i] = rand.nextFloat(); 
    rndY[i] = rand.nextFloat(); 
} 
+0

返回半开范围内的伪随机均匀分布浮点[0.0,1.0)。 – g00dy