开发者

Strange exception

Hey guys we are trying to make a client-server racing game for our semester project but we have some strange error

public void updatePosition(int id, ArrayList<Point2D.Float> positions){
    if(开发者_JS百科id==1){
        for (int i = 1; i < game.getS().getVehicles().size(); i++)
        {
            game.getS().getVehicles().get(i).updatePosition(positions.get(i));              
        }

    }else if(id==2){
        game.getS().getVehicles().get(1).updatePosition(positions.get(0));              
        for (int i = 2; i < game.getS().getVehicles().size(); i++)
        {
            game.getS().getVehicles().get(i).updatePosition(positions.get(i));  
        }

this is our code

and the exception is in this exact row: game.getS().getVehicles().get(1).updatePosition(positions.get(0));


References are initialized to null by default. If you create a collection or array, and fail to initialize references, they'll be null by default.


A NullPointerException can occur in many places in this small fragment of code.

Basically, when you have an expression of the kind a.b().c(), a NullPointerException can be thrown if a is null, or if b() returns null.

If you are uncertain that all of the parts of such an expression are not null, you have to perform explicit checking:

if (a != null) {
  WhateverObject intermediate = a.b();

  if (intermediate != null) {
    intermediate.c(); 
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜