在Java中,如何初始化字符串数组?

时间:2013-05-20 12:51:44

标签: java arrays string initialization

我想要做的是初始化一个字符串数组,然后用不同的字符串填充每个空格,如下所示:

        int year = 1995; //the current year i'm working with

        String[] Year; //Initialize the year string
        String j;


        for(int i=(year-50); i < year; i++)
        {
            j = Integer.toString(i); //Converts the integer to a string
            Year[i] = j; //EXCEPTION OCCURS HERE WHEN I SET 'String[] Year'
                         //equal to 'null'

        }

问题是我无法初始化字符串,因为我收到以下错误: '本地变量Year可能尚未初始化'

如果我设置String[] Year = null,那么我可以初始化字符串。但是,如果我这样做,则在尝试运行时会抛出异常。编译代码:java.lang.NullPointerException

我知道我的代码可能更短,但我试图找出问题...

5 个答案:

答案 0 :(得分:1)

使用此代码:

String[] Year = new String[50]; //Initialize the year string

现在Java知道你想要数组的长度,所以它可以初始化它。

如果你没有告诉Java你希望你的数组有多长,它就无法生成数组,因为它不知道数组应该有多长。

此外,如果您想轻松调整,可以使用final变量SIZE

此外,您不需要字符串j,因为在将其添加到数组之前,您只使用它来存储某些内容的结果。

这不会影响您的代码,但正确的Java命名约定是变量应以小写字母开头,因此将Year更改为years

因此,您的代码可以像这样改进:

    int year = 1995; //the current year i'm working with
    final int SIZE = 50; //how big

    String[] years = new String[SIZE]; //Initialize the year string

    for(int i=(year-SIZE); i < year; i++) //Note the use of the SIZE variable
    {
        years[i] = Integer.toString(i);
    }

答案 1 :(得分:1)

U没有初始化年份变量,同样,年份数组中没有项目

String[] Year = new String[50]; // Initlaize adn add Some content

答案 2 :(得分:0)

您需要在具有所需大小的数组上执行新操作

String[] Year = new String[desired size];

如果不这样做,就不会在内存中创建数组,因此你会遇到异常。

答案 3 :(得分:0)

您尚未初始化Year

String[] years = new String[SIZE];  

String[] years;  
years = new String[SIZE];

String[] years = {"Hello","World","Again"};

此外,使用正确的Java命名约定。

答案 4 :(得分:0)

String[] Year;仅声明具有名称年份的数组引用,您需要在使用之前声明具有所需长度的数组,因此必须将其设为

String[] years = new String[size]; 

其中'size'是您要定义的数组的长度。另外String[] year=null只会创建一个指向null的引用,这就是你得到NullPointerException的原因。

相关问题