本文介绍了为什么这个for循环给出一个空指针异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为学校创建一个小游戏,但是当我尝试这样做来填充这个数组中的x和y变量时,我得到了一个N​​PE。
任何人都可以帮忙吗?

pre $ public $ {
public static void main(String [] args) {
Gra piece [] = new Gra [10];

for(int i = 0; i< piece.length; i ++){
piece [i] .x = 50;
piece [i] .y = 50;
}
}
}

class Gra {
public int x = 50;
public int y = 10;

$ / code>


解决方案
  Gra piece [] = new Gra [10]; 

不初始化数组内的对象,只创建数组,所以调用构造函数来创建 Gra s

  for(int i = 0; i< piece.length; i ++){
piece [i] = new Gra();
piece [i] .x = 50;
piece [i] .y = 50;
}


Hi there i'm creating a small game for school, but when i try to do this to fill out the x and y variables in this array i get a NPE.Could anyone help?

public class mainclass {
    public static void main(String[] args) {
        Gra piece[] = new Gra[10];

        for (int i = 0; i < piece.length; i++) {
            piece[i].x = 50;
            piece[i].y = 50;
        }
    }
}

class Gra{
    public int x = 50;
    public int y = 10;
}
解决方案
Gra piece[] = new Gra[10];

does not initialize objects inside the array, it only creates array, so call constructor to create Gras

for (int i = 0; i < piece.length; i++) {
   piece[i] = new Gra();
   piece[i].x = 50;
   piece[i].y = 50;
}

这篇关于为什么这个for循环给出一个空指针异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 08:51
查看更多