空指针异常(遍历对象数组)

huangapple go评论70阅读模式
英文:

Null Pointer Exception (Looping through an array of objects)

问题

我有一段时间没有使用Java了,所以有些生疏。我有一个返回对象数组的方法。在我的主程序中,我创建了一个新的对象数组,并将这个新的对象数组设置为方法的返回数组。类似这样:

Obj[] main_arr = new Obj[100];
main_arr = method(x);

for (int i = 0; i < main_arr.length; i++) {
  if (main_arr[i].number == 1) {  // 错误似乎在这里
      // 做一些操作
  } else {
      // 做一些操作
  }
}

我试图遍历 main_arr 并访问这个对象数组中的内容,但是我得到了一个空指针异常。我已经使用调试工具查看过了,main_arr 似乎有正确的内容。有任何想法是为什么吗?提前谢谢你!

英文:

I haven't used Java in a while so I'm rusty. I have a method that returns an array of objects. In my main, I created a new object array and set that new array of objects to the return array of the method. Something like this:

Obj[] main_arr = new Obj[100];
main_arr = method(x);

for (int i = 0; i &lt; main_arr.length; i ++){
  if(main_arr[i].number == 1) {  // the error seems to be here
      // do some stuff
  }
  else {
      // do some stuff
  }

}

I am trying to loop through main_arr and access the things in this object array, however I get a Null Pointer Exception. I've been in the debugger tool and main_arr seems to have the correct content. Any ideas why? Thank you in advance!

答案1

得分: 1

一些 main_arr 中的元素是空的。

这可能发生在,例如,main_arr 有 100 个元素,但只有前 10 个实际上被赋值了值。

英文:

Some elements of main_arr are null.

This could happen, for example, if main_arr has 100 elements but only the first 10 were actually assigned a value.

答案2

得分: 0

"main_arr.length()" 不是正确的写法,应该是 "main_arr.length"。

英文:

It's main_arr.length() not main_arr.length

答案3

得分: 0

Java数组对象没有获取其长度的方法。您需要使用'数组长度属性',如下所示:

int arrayLength = myArray.length;
for (int i = 0; i <= arrayLength - 1; i++) {
   if (myArray[i] == whatever) {
      //做一些操作
   }
}

来源:https://www.edureka.co/blog/array-length-in-java/

英文:

Java Array Object does not have a method to get its length. Youneed to use the ‘array length attribute’, like this:

int arrayLength = myArray.length;
for (int i = 0; i &lt;= arrayLength - 1; i++) {

   if (myArray[i] == whatever) {
      //do some job
   }
}

Credits: https://www.edureka.co/blog/array-length-in-java/

huangapple
  • 本文由 发表于 2020年4月4日 08:28:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/61022328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定