简体   繁体   English

Java:线程中的数组异常

[英]Java: Arrays Exception in thread

Why the code doesn't print out the variable count that I changed threw creating array object? 为什么代码没有打印出我更改的变量计数,而创建了数组对象?

public class EchoTestDrive {
public static void main(String args[]) {
    Echo[] pets;
    pets = new Echo[7];
    pets[0] = new Echo();
    pets[0].count = 43;
    pets[1].count = 50;
    **System.out.println(pets[0].count);**//doesn't prints out
    **System.out.println(pets[1].count);**//doesn't prints out
    //prints out: Exception in thread "main" java.lang.NullPointerException
    // at EchoTestDrive.main(EchoTestDrive.java:8)
}
}

Another class : 另一类

public class Echo {
int count = 0;
void hello(){
    System.out.println("helloooo... ");
   }
}
pets[1].count = 50;

This will raise java.lang.NullPointerException as pets[1] reference is null . 由于pets[1] reference为null因此将引发java.lang.NullPointerException

System.out.println(pets[0].count);

If you commented out the previous line, then this will definitely print 43. 如果您注释掉了前一行,那么肯定会打印43。

System.out.println(pets[1].count);

If commented out pets[1].count = 50; 如果注释掉了, pets[1].count = 50; line, then it would raise same java.lang.NullPointerException as pets[1] reference is null . 行,则将引发相同的java.lang.NullPointerException因为pets[1]引用为null

In short you forgot to initialise pets[1] which should be - 简而言之,您忘了初始化pets[1] ,该pets[1]应为-

pets[1] = new Echo();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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