数组初始化给出空指针异常 [英] Array initialization gives null pointer exception

查看:136
本文介绍了数组初始化给出空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在学习Java并且正在尝试使用类。但是我无法初始化数组对象

I am learning Java recently and was trying to work with classes.But I am not able to initialize array objects

 class Tablet
 {
    String S = null;
    void set(String a)
    {
        S = a;
    }
}

public class questions
{

public static void main(String args[])
{

    Tablet[] T = new Tablet[6];
    for(int i = 0;i<6;i++)
    {
        T[i].set("111"); // I get null pointer exception here
    }

    //solution(T,6);
} 
}

谁能告诉我哪里出错了?

can anybody tell me where I am going wrong?

推荐答案

当你这样做时

Tablet[] T = new Tablet[6];

您正在创建引用数组(即引用变量数组)不指向其他地方,即它们是null。您需要将对象分配给数组中上面创建的引用变量。

You are creating array of references(i.e Array of reference variables) which are not pointing to anywhere else i.e they are null.You need to assign objects to above created reference variables in array.

Tablet[] T = new Tablet[6];
    for(int i = 0;i<6;i++)
    {
        T[i]=new Tablet();
        T[i].set("111"); // No Null Pointer Exception Now
    }

这篇关于数组初始化给出空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆