【问题标题】:why i have this Exception in java : Exception in thread "main" java.lang.NullPointerException为什么我在java中有这个异常:线程“main”java.lang.NullPointerException中的异常
【发布时间】:2014-12-05 16:57:55
【问题描述】:

这是我的主要代码:

Scanner input= new Scanner(System.in);

Student[] starray=new Student[5];

for (int i=0; i<3; i++)
{
    System.out.println("enter:");
    starray[i].name=input.next();   
    System.out.println("enter:");
    starray[i].family=input.next(); 
    System.out.println("enter:");
    starray[i].sid=input.nextInt();
}      
for(int i=0; i<3; i++)
        System.out.println(starray[i].name);

我只有一门课:

String name,family;
Integer sid;

Student(){
       name="kh";
       family="kh";
       sid=0;}

当我运行它时,出现以下异常: 线程“主”java.lang.NullPointerException 中的异常 在 testcodes.TestCodes.main(TestCodes.java:19) Java 结果:1

【问题讨论】:

  • 您有实际问题吗?
  • 你没有在数组中创建任何学生......我所看到的是你正在制作数组但没有创建new Student()@Chrismas007 我认为他的问题在标题中...... .
  • @3kings 在 Triage 中看到了这个,所以我无法进行编辑。

标签: java arrays for-loop nullpointerexception


【解决方案1】:

Student[] starray = new Student[5]; 只创建 容器。该容器中的每个元素都是null

您需要依次创建每一个。在你的循环中,考虑

starray[i] = new Student();

更好的是,为Student 构建一个强类型构造函数,将名称等作为参数。这将有助于提高程序的稳定性。

【讨论】:

    【解决方案2】:

    在这种情况下,Java 与 C++ 非常相似。在 C++ 中,当您声明一个对象数组时,所有对象都还没有被初始化(其中没有真正的对象),换句话说,数组只是对象的 占位符

    所以你的陈述

    Student[] starray = new Student[5];
    

    在视觉上可以是

    starray --> +------+------+------+------+------+
                | null | null | null | null | null |
                +------+------+------+------+------+
    

    在这句话之后

    starray[0] = new Student();
    

    starray --> +------+------+------+------+------+
                |      | null | null | null | null |
                +---|--+------+------+------+------+
                    |
                    v
                +------------------+
                | Student Instance |
                +------------------+
    

    【讨论】:

      猜你喜欢
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 2016-02-05
      • 1970-01-01
      • 2023-03-10
      • 2013-04-30
      相关资源
      最近更新 更多